2015-02-23 71 views
0

全部。在尝试使用python的email包与smtplib一起发送电子邮件时遇到了一些问题。我已经设置了一个发送电子邮件的功能,它运行良好,除了电子邮件总是没有主题。我对python并不陌生,但对于像这样的与互联网相关的东西,我是新手。我已经在本论坛中的几个答案以及documentation中的示例中设置了以下内容。用python发送邮件 - 邮件丢失主题

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('[email protected]',['[email protected]'],'This is the subject','Hello, World!')会导致电子邮件正确发送但没有主题。

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

我很感激任何帮助。

回答

1

不是传递主题作为参数传递给MimeMultipart的,尽量的值赋给消息:

msg['Subject'] = subject

很好的例子,在docs:https://docs.python.org/3/library/email-examples.html

+0

我已经试过了,在没有工作第一。对不起,我忘了在邮件中提到。但是,既然你说过,我又试了一次,结果奏效了。我意识到不同之处在于我只是将代码行添加到代码中,因此我在第一次调用MIMEMultipart时设置了主题,然后再次执行了msg ['Subject'] = subject',并且它没有没有工作。然而,从我的'MIMEMultipart'调用中删除'Subject = subject'选项,然后添加你的行,确实有效。你知道为什么会发生吗? – TomCho 2015-02-24 11:57:48

+0

MIMEMultipart子类为Message类。该类有一个称为[keys](https://docs.python.org/3/library/email.message.html#email.message.Message.keys)的方法,当被调用时,它显示消息的标题。我相信主题必须添加为邮件的标题,您可以通过将主题的值分配给“主题”键进行添加,如上所示。 – 2015-02-24 15:20:49