使用python发送电子邮件 - 消息主题丢失

时间:2015-02-23 19:40:43

标签: python email

所有。尝试使用python的email包和smtplib发送电子邮件时遇到了一些问题。我已经设置了一个发送电子邮件的功能,它运行良好,但电子邮件总是没有主题。我不是python的新手,但我很擅长将它用于与互联网相关的事情,比如这个。我在本论坛的几个答案以及documentation中的示例中设置了以下内容。

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()

将该功能调用为send_mail('john@doe.com',['john@doe.com'],'This is the subject','Hello, World!')会导致电子邮件正确发送但没有主题。

带或不带文件的输出是相同的。此外,阅读文档也没有帮助我。

我感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

不要将subject作为参数传递给MIMEMultipart,而是尝试将值赋给msg:

msg['Subject'] = subject

文档中的好例子:https://docs.python.org/3/library/email-examples.html