我有最奇怪的错误。我正在使用 smtplib 从 gmail 帐户发送电子邮件。每次我运行脚本时,我都会看到消息显示在我用来发送的 gmail 帐户的“已发送”选项卡中。但是有时在接收端没有收到消息。
我注意到消息正文的长度与我是否收到它之间存在相关性。每次都会收到一条“foo”的消息,而我想要的大约 200 个字符长的消息永远不会收到。我尝试发送正文长度在 0 到 60 之间的消息。这两次我都尝试过,这 60 个都显示在发送 gmail 帐户的“已发送”文件夹中,但只有以下内容显示在接收电子邮件帐户中:
这是我用来发送消息的代码:
for i in range(100):
mail('someaddress@gmail.com','testing limit',str(i) + "a"*i)
这是邮件功能:
def mail(to, subject, text, attach=None):
"""Sends an email, formatted as HTML to list of senders with an optional attachment.
Specifically, the 'to' argument must be a comma seperated list of email addresses.
'subject' and 'text' are what appear in the email subject and body, respectively and
'attach' is a path to an attachment.
"""
msg = MIMEMultipart()
# build the email header
msg['From'] = 'A Concerned Robot'
msg['To'] = to
msg['Subject'] = subject
# attach our body text as html
msg.attach(MIMEText(text,'html'))
# attach the attachment if its there
part = MIMEBase('application', 'octet-stream')
if attach is not None:
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
# open up a line with the server
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
# login, send email, logout
mailServer.login(conf.user, conf.pw)
mailServer.sendmail(conf.user, to, msg.as_string())
mailServer.close()