用python中的smtp发送电子邮件时,my\t将替换为一个空格。

2024-06-10 04:57:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要能够有标签在我发送的电子邮件,以便内容可以复制粘贴到excel。代码:

SUBJECT = subj
TO = [whoto]
FROM = whofrom
BODY = string.join((
    "From: %s" % FROM,
    "To: %s" % ", ".join(TO),
    "Subject: %s" % SUBJECT ,
    "",
    text
    ), "\r\n")

server = smtplib.SMTP(host)
server.login(log,pass)
server.sendmail(FROM, TO, BODY)
server.quit()

我的文本中有标签页,但当电子邮件发送时没有标签页。我怎样才能让标签保留下来呢。在


Tags: to代码from内容server电子邮件body标签
1条回答
网友
1楼 · 发布于 2024-06-10 04:57:40

我建议使用mime编码器库:

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import smtplib
import datetime
import logging

class mailer:
    def __init__(self,SERVER="my.mail.server",FROM="email@mydomain.com"):
        self.server = SERVER
        self.send_from = FROM
        self.logger = logging.getLogger('mailer')

    def send_mail(self, send_to, subject, text, files=[]):
        assert type(send_to)==list
        assert type(files)==list
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug(' '.join(("Sending email to:",' '.join(send_to))))
            self.logger.debug(' '.join(("Subject:",subject)))
            self.logger.debug(' '.join(("Text:",text)))
            self.logger.debug(' '.join(("Files:",' '.join(files))))
        msg = MIMEMultipart()
        msg['From'] = self.send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        msg.attach( MIMEText(text) )
        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)
        smtp = smtplib.SMTP(self.server)
        mydict = smtp.sendmail(self.send_from, send_to, msg.as_string())
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug("Email Successfully Sent!")
        smtp.close()
        return mydict

一定要检查返回字典,因为它会让你知道如果只有一些人收到电子邮件。在

相关问题 更多 >