使用python来发送邮件

in 默认分类 with 0 comment

在python中,我们可以通过email包来创建邮件,然后通过smtplib包来发送邮件,这在官方的文档中也有示例:email-examples
下面我们以使用smtps发送一封MIME内容类型的邮件为例:

mail_user = '[email protected]'
password = 'password'
from_addr = f'test <{mail_user}>'
to_addr = '[email protected]'
mail_host = 'example.com'
from email.mime.text import MIMEText

msg = MIMEText('smtp test', 'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'smtp test'
import smtplib

# smtps
server = smtplib.SMTP_SSL(mail_host)
# smtp
# server = smtplib.SMTP(mail_host)
server.login(mail_user, password)
server.sendmail(mail_user, [to_addr], msg.as_string())
server.quit()

但是,我们按照上述代码发送邮件后,在RSPAMD(一个反垃圾邮件系统)中会获得一个较高的垃圾邮件评分,在我这会是4.50 / 15,容易被认为是垃圾邮件。
为何会出现这种情况呢,仔细查看RSPAMD的history,发现影响评分的原因有如下

其中,MISSING_MID 是由于缺少了message id, MISSING_DATE是由于缺少了message date,所以我们需要在创建邮件时加入对应的头:

from email.utils import make_msgid, formatdate

msg['Message-ID'] = make_msgid('test',mail_host)
msg["Date"] = formatdate(localtime=True)

现在查看RSPAMD的历史,发现评分已经变为了1.00 / 15 分,至于为何还是高于0分,可以看到影响评分的原因为:

msg = MIMEText('smtp test', 'plain')

此时RSPAMD的评分已经变为-0.10 / 15 分:

msg = MIMEText('smtp测试', 'plain', 'utf-8')

那么RASPAMD得到的分数将为0.00 / 15 分:

最后,我们总结一下python发送邮件的完整代码为:

from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate
import smtplib

# configuration
mail_user = '[email protected]'
password = 'password'
from_addr = f'test <{mail_user}>'
to_addr = '[email protected]'
mail_host = 'example.com'

# ascii text
msg = MIMEText('smtp test', 'plain')
# contain unicode characters
# msg = MIMEText('smtp测试', 'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'smtp test'

msg['Message-ID'] = make_msgid('test',mail_host)
msg["Date"] = formatdate(localtime=True)


# smtps
server = smtplib.SMTP_SSL(mail_host)
# smtp
# server = smtplib.SMTP(mail_host)
server.login(mail_user, password)
server.sendmail(mail_user, [to_addr], msg.as_string())
server.quit()