Python2.7发送邮件,为什么msg ['To']保持空白?

时间:2016-12-29 11:28:51

标签: python email

我使用python脚本发送多个收件人邮件,但它可以正常工作,但在邮件的“收件人”中,该字段为空。在我试过的每个邮件提供商上。

这是我的代码:

def send_mail(self, server, send_from, subject, attach, foo=None, bar=None)
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['Subject'] = subject

    body = u"""<html> My Body </html>"""

    #Attach file pdf
    msg.attach(MIMEText(body, 'html', 'utf-8'))
    filename = 'fname.pdf'
    attachment = open(attach, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename = %s" % filename)
    msg.attach(part)

    text = msg.as_string()

    if foo != None and bar != None:
        recipients = ["a@b.fr", "b@b.fr"]
        msg['To'] = ", ".join(recipients)
        server.sendmail(send_from, recipients, text)
    else:
        msg['To'] = "c@b.fr"
        server.sendmail(send_from, msg['To'], text)
    sleep(1)

msg ['To']应该是我邮件中的“收件人”,但它仍然是空的。 (即使在只有一个收件人的“其他”中)。我在现有问题上找不到任何帮助,所以我来征求你的帮助。

2 个答案:

答案 0 :(得分:0)

根据文档,第二个参数是收件人列表。你需要改变你的行

... in provinces ... ng-keydown=getProvince($viewValue) ... in html

server.sendmail(send_from, msg['To'], text)

答案 1 :(得分:0)

终于找到了:

text = msg.as_string()应在分配到msg['To']之后完成因此,它会出现在我ifelse juste server.sendmail(send_from, msg['To'], text)之前,因为所有信息都已写入在邮件中,甚至是&#39; To&#39;和&#39; From&#39;在第三个参数text