Python邮件发送的主题缺失问题及解决方法

130 阅读2分钟

在使用Python的email包和smtplib发送电子邮件时,发现电子邮件总是没有主题。虽然在用法上有一定的经验,但对于互联网相关的应用(如电子邮件发送)还比较陌生。在查阅了论坛中的多个解答和文档中的示例后,我设置了如下代码:

` import smtplib from os.path import basename from email import encoders from email.mime.application import MIMEApplication from email.mime.base import MIMEBase from email.mime.audio import MIMEAudio from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None, server="smtp.gmail.com"): import mimetypes assert isinstance(send_to, list) msg = MIMEMultipart(From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject) msg.attach(MIMEText(text)) for f in files or []: print f ctype,encoding=mimetypes.guess_type(f) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(f) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(f, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(f, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(f, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=basename(f)) smtp = smtplib.SMTP(server) smtp.starttls() usrname=send_from pwd=raw_input("Type your password:") smtp.login(usrname,pwd) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()

`

当使用上述代码发送电子邮件时,收到的电子邮件中并没有主题。无论是否带附件,结果都是相同的。查阅文档也没有找到解决方法。

2、解决方案

按照第一个回复中的建议,将subject作为参数传递给msg,而不是MIMEMultipart:

msg['Subject'] = subject

这样,电子邮件就可以正确发送,并且具有主题。

以下是改进后的代码:

def send_mail(send_from, send_to, subject, text, files=None, server="smtp.gmail.com"):
    import mimetypes
    assert isinstance(send_to, list)
    msg = MIMEMultipart(From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True))
    msg['Subject'] = subject  # Add the subject to the message
    msg.attach(MIMEText(text))
    for f in files or []:
            print f
            ctype,encoding=mimetypes.guess_type(f)
            if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                    fp = open(f)
                    msg = MIMEText(fp.read(), _subtype=subtype)
                    fp.close()
            elif maintype == 'image':
                    fp = open(f, 'rb')
                    msg = MIMEImage(fp.read(), _subtype=subtype)
                    fp.close()
            elif maintype == 'audio':
                    fp = open(f, 'rb')
                    msg = MIMEAudio(fp.read(), _subtype=subtype)
                    fp.close()
            else:
                    fp = open(f, 'rb')
                    msg = MIMEBase(maintype, subtype)
                    msg.set_payload(fp.read())
                    fp.close()
                    encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=basename(f))
    smtp = smtplib.SMTP(server)
    smtp.starttls()
    usrname=send_from
    pwd=raw_input("Type your password:")
    smtp.login(usrname,pwd)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()