SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
Python创建 SMTP 对象
语法:
import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
参数说明:
host—SMTP 服务器主机。可以指定主机的ip地址或者域名如: 51coding.com,这个是可选参数。
port— 如果提供了 host 参数, 需要指定 SMTP 服务使用的端口号,一般情况下 SMTP 端口号为25。
local_hostname—如果 SMTP 在本机上,只需要指定服务器地址为 localhost 即可。
使用Python SMTP发送邮件
Python SMTP对象使用sendmail方法发送邮件,语法如下:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
参数说明:
from_addr—邮件发送者地址。
to_addrs— 字符串列表,邮件发送地址。
msg— 发送消息
实例:
#!/usr/bin/pythonimport smtplibsender = 'from@fromdomain.com'receivers = ['to@todomain.com']message = """From: From Person <from@fromdomain.com>To: To Person <to@todomain.com>Subject: SMTP e-mail testThis is a test e-mail message."""try:smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message)print "Successfully sent email"except SMTPException:print "Error: unable to send email"
使用Python发送HTML格式的邮件
Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。
实例:
#!/usr/bin/python# -*- coding: UTF-8 -*-import smtplibfrom email.mime.text import MIMETextfrom email.header import Headersender = 'from@fromdomain.com'receivers = [''to@todomain.com''] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱mail_msg = """<p>Python 邮件发送测试...</p><p><a href="http://www.51coding.com">这是一个链接</a></p>"""message = MIMEText(mail_msg, 'html', 'utf-8')message['From'] = Header("wiki", 'utf-8')message['To'] = Header("测试", 'utf-8')subject = 'Python SMTP 邮件测试'message['Subject'] = Header(subject, 'utf-8')try:smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message.as_string())print "邮件发送成功"except smtplib.SMTPException:print "Error: 无法发送邮件"
Python 发送带附件的邮件
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
实例:
#!/usr/bin/python# -*- coding: UTF-8 -*-import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Headersender = 'from@fromdomain.com'receivers = ['to@todomain.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱#创建一个带附件的实例message = MIMEMultipart()message['From'] = Header("wiki", 'utf-8')message['To'] = Header("测试", 'utf-8')subject = 'Python SMTP 邮件测试'message['Subject'] = Header(subject, 'utf-8')#邮件正文内容message.attach(MIMEText('这是wiki Python 邮件发送测试……', 'plain', 'utf-8'))# 构造附件1,传送当前目录下的 test.txt 文件att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')att1["Content-Type"] = 'application/octet-stream'# 这里的filename可以任意写,写什么名字,邮件中显示什么名字att1["Content-Disposition"] = 'attachment; filename="test.txt"'message.attach(att1)# 构造附件2,传送当前目录下的 imooc.txt 文件att2 = MIMEText(open('imooc.txt', 'rb').read(), 'base64', 'utf-8')att2["Content-Type"] = 'application/octet-stream'att2["Content-Disposition"] = 'attachment; filename="imooc.txt"'message.attach(att2)try:smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message.as_string())print "邮件发送成功"except smtplib.SMTPException:print "Error: 无法发送邮件"
