python smtplib在没有收件人

时间:2015-07-23 10:15:53

标签: python email smtplib

我使用python smtplib发送电子邮件。他们到达目的地,但是" To"字段丢失。 在Gmail中," To"领域是空的,但雷鸟说"未公开的收件人"。我做了一些谷歌搜索,但我没有找到任何东西。

我没有看到解释这个问题的代码有任何错误,但是我正在关注Stack Overflow的另一个问题的一些代码片段,所以可能是我错过了什么。

这是邮件发件人的代码:

def connect_and_send(send_from, send_to, carbon_copy, msg):
    confp = ConfigParser()
    confp.read("config/mail.ini")
    server  = str(confp.get('mail', 'host'))
    port    = str(confp.get('mail', 'port'))
    user    = str(confp.get('mail', 'username'))
    password= str(confp.get('mail', 'password'))
    smtp = smtplib.SMTP_SSL()
    smtp.connect(server, port)
    smtp.login(
        user,
        password
    )
    send_to.append(carbon_copy)
    smtp.sendmail(send_from, send_to, msg.as_string())


def send_mail(send_from, send_to, carbon_copy, subject, text, signature, files=None):
    assert isinstance(send_to, list)
    if ARGS.debug:
        print "MAIL to:", send_to
        print "MAIL from:", send_from
        print "MAIL subject", subject
        print "with {0} files attached".format(len(files))
    msg = MIMEMultipart('alternative')
    msg["Subject"] = subject
    msg["From"] = send_from
    msg["Date"] = formatdate(localtime=True)
    msg["To"] = COMMASPACE.join(send_to)

    msg.attach(MIMEText(text+"\n"+signature))
    for f in files or []:
        part = MIMEBase('image', "png")
        part.set_payload(f[1].read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="{0}.png"'.format(f[0]))
        msg.attach(part)

    if ARGS.debug and not ARGS.force_send:
        print msg.as_string()
    else:
        connect_and_send(send_from, send_to, carbon_copy, msg.as_string())

1 个答案:

答案 0 :(得分:0)

您可以尝试yagmail(完全透露:我是开发人员)。

完整的代码是:

import yagmail
yag = yagmail.SMTP(send_from, host = host, port = port)
if files is None:
    files = []
yag.send(send_to, subject, contents =  [text, signature] + files, bcc = carbon_copy)

请注意,文件已经巧妙地附加了! (鉴于它们是文件名的本地路径)

我还建议使用yagmail的密钥环来防止必须在本地存储密码。

你可以从pip获得yagmail:

pip install yagmail   # python 2
pip3 install yagmail  # python 3

此外,由于您似乎正在使用某些非常具体的邮件需求,因此我确信您可以从yagmail中受益,并且应该知道阅读github documentation。随意提出问题/请求。

相关问题