Python电子邮件发送,标题似乎是空的,被拒绝为垃圾邮件

时间:2017-10-24 09:36:04

标签: python python-3.x email

我正在尝试使用一个非常简单的python脚本发送带有zip附件的电子邮件,该脚本来自之前帖子中的答案。

我的脚本看起来像这样:

import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

to_addres = "*******"
from_addr = "*******"
mail_server = "*******"
zf = open("/home/******/asd.zip", "rb")


text = '''
Hello,

Here is your test email.

Cheers!
'''
msg = MIMEMultipart(text)
msg.add_header('From', from_addr)
msg.add_header("To", to_addres)
msg.add_header("Subject", "Test")

attachemnt = MIMEBase('application', 'zip')
attachemnt.set_payload(zf.read())
encoders.encode_base64(attachemnt)
attachemnt.add_header('Content-Disposition', 'attachment', filename="asd.zip")
msg.attach(attachemnt)

server = smtplib.SMTP(mail_server, 25)
server.ehlo()
server.sendmail(from_addr, to_addres, msg.as_string())
server.close()

一切似乎都很好,但是当我从我的提供商发送电子邮件到测试GMAIL帐户时,我被阻止为垃圾邮件。

我回来的部分错误消息:

 -0.6 RP_MATCHES_RCVD        Envelope sender domain matches handover relay domain
  2.1 MISSING_HEADERS        Missing To: header
 -0.1 BAYES_00               BODY: Bayes spam probability is 0 to 1%
                             [score: 0.0000]
  0.0 TVD_SPACE_RATIO        No description available.
  1.0 MISSING_DATE           Missing Date: header
  1.0 MISSING_MID            Missing Message-Id: header
  1.8 MISSING_SUBJECT        Missing Subject: header
  1.0 MISSING_FROM           Missing From: header
  0.7 MIME_HEADER_CTYPE_ONLY 'Content-Type' found without required MIME
                             headers
X-ACL-Warn: condition = yes

所以看来电子邮件标题是空的?怎么会这样?我做错了什么?

1 个答案:

答案 0 :(得分:4)

此行负责解决问题:

msg = MIMEMultipart(text)

它将text(多行字符串)添加到Content-Type标题中。这会创建无效的邮件格式。

请改为:

msg = MIMEMultipart()
msg.attach(MIMEText(text, 'plain'))

必须从MIMEText

导入email.mime.text