Python smtplib - 发送邮件后没有收件人

Python smtplib - No recipient after sending mail

我最近写了一个脚本,如果我想监视的网站使用 smtplib 发生了更改,它会向我发送一封电子邮件。该程序有效,我收到了电子邮件,但是当我查看已发送的电子邮件时(因为我正在从同一帐户向自己发送电子邮件),它说没有收件人或 'To:' 地址,只有密件抄送我希望将电子邮件发送到的地址。这是 smtplib 的一个特性吗——它实际上不添加 'To:' 地址,只添加密件抄送地址?代码如下:

if (old_source != new_source):

# now we create a mesasge to send via email
fromAddr = "example@gmail.com"
toAddr = "example@gmail.com"
msg = ""

# smtp login
username = "example@gmail.com"
pswd = "password"

# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()

尝试手动将 headers 添加到您的消息中,用空行与 body 分隔,例如:

...
msg="""From: sender@domain.org
To: recipient@otherdomain.org
Subject: Test mail

Mail body, ..."""
...

试试这个,似乎对我有用。

#!/usr/bin/python

#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = 'example@gmail.com'
receivers = ['example@gmail.com']


msg = MIMEMultipart()
msg['From'] = 'example@gmail.com'
msg['To'] = 'example@gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))

ServerConnect = False
try:
    smtp_server = SMTP('smtp.gmail.com','465')
    smtp_server.login('#####@gmail.com', '############')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

if ServerConnect == True:
    try:
        smtp_server.sendmail(sender, receivers, msg.as_string())
        print "Successfully sent email"
    except SMTPException as e:
        print "Error: unable to send email", e
    finally:
        smtp_server.close()

按如下方式更新代码即可解决问题:

if (old_source != new_source):

# now we create a mesasge to send via email
fromAddr = "example@gmail.com"
toAddr = "example@gmail.com"
msg = ""

# smtp login
username = "example@gmail.com"
pswd = "password"

# create server object and login to the gmail smtp

server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
header = 'To:' + toAddr + '\n' + 'From: ' + fromAddr + '\n' + 'Subject:testing \n'
msg = header + msg
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()

只是把它扔在那里:请尝试 yagmail。免责声明:我是维护者,但我觉得它可以帮助大家!

它确实提供了很多默认值:我很确定您可以直接发送电子邮件:

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)

这也会设置 headers :)

您必须先安装 yagmail

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

如果您还想嵌入 html/images 或添加附件,您会非常 喜欢这个包!

它还可以防止您在代码中输入密码,从而使它更加安全。