我使用的脚本非常相似;我在这里发布它作为如何使用电子邮件。*模块生成MIME消息的示例;所以这个脚本可以很容易地修改为附加图片等。
我依靠我的ISP添加日期时间标题。
我的ISP要求我使用安全SMTP发送邮件,我靠ssmtplib模块(在http://www1.cs.columbia.edu/~db2501/ssmtplib.py下载)
在你的脚本,用户名和密码,(下面给出虚值),用于在SMTP服务器上进行身份验证,在源文件中以纯文本格式。这是一个安全弱点;但最好的选择取决于你需要多么谨慎(想要?)来保护这些。
=======================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = '[email protected]_email_domain.net'
destination = ['[email protected]_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except Exception, exc:
sys.exit("mail failed; %s" % str(exc)) # give a error message
确保您获得日期/时间正确。我发现以下功能非常有用,它为Date-Header提供了完美格式化的值: http://docs.python.org/py3k/library/email.util.html#email.utils.formatdate – BastiBen 2010-07-30 06:11:21
这里是一个代码示例,允许[在主题和/或正文中发送带有Unicode文本的电子邮件](http://stackoverflow.com/a/20787826/4279) – jfs 2013-12-26 18:10:11
这里是一个代码示例,演示如何[发送图像内联电子邮件与HTML和纯文本部分)](http://stackoverflow.com/a/20485764/4279)。它还展示了如何在旧的Python版本上配置ssl参数。 – jfs 2013-12-26 18:11:00