SMTP: 简单传输协议, 实在 Internet 上传输 Email 的事实标准.
Python 的 smtplib 模块提供了一种很方便的途径来发送电子邮件, 它对 SMTP 协议进行了简单的封装.
python 中发送邮件除了 SMTP 模块外, 还需用到 email 模块. email 模块主要用来定义邮件的标题, 正文, 附件.
一, SMTP 的方法
1,SMTP 模块的方法
connect(host,port)
host: 指定连接的邮箱服务器
port: 指定连接服务器的端口号
login(user,passwork)
user: 登陆邮箱用户名
password: 登陆邮箱密码
sendmail(from_addr,to_addrs,msg,...)
from_addr: 邮件发送者地址
to_addrs: 收件人, 字符串列表
msg: 发送的消息
quit() 方法: 结束 SMTP 会话
2,email 模块的方法
email.mime.text.MIMEText() 用来定义邮件正文
email.header.Header() 用来定义邮件标题
email.mime.multipart.MIMEMultipart() 定义邮件附件
二, 自动发送 html 邮件
- # coding:utf-8
- import unittest, time,smtplib
- from email.mime.text import MIMEText
- from email.header import Header
- smtpserver = 'smtp.qq.com'
- user = 'username@qq.com'
- password = 'password'
- sender = 'username@qq.com'
- receiver = 'receive@163.com'
- subject = 'Python email test'
- # 编写 HTML 类型的邮件正文
- msg = MIMEText('<html><h1>Test! </h1></html>', 'html', 'utf-8')
- msg['Subject'] = Header(subject, 'utf-8') #邮件主题
- # 连接发送邮件
- smtp = smtplib.SMTP()
- smtp.connect(smtpserver)
- smtp.login(user, password)
- smtp.sendmail(sender, receiver, msg.as_string())
- smtp.quit()
收到的邮件如下:
三, 发送带附件的邮件
- # coding:utf-8
- import unittest, time,smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- smtpserver = 'smtp.qq.com'
- user = 'username@qq.com'
- password = 'password'
- sender = 'username@qq.com'
- receiver = 'receiver@163.com'
- subject = 'Python email test'
- sendfile = open('E://report//test.txt', 'rb').read() #要发送的附件
- # 发送带附件的邮件
- attach = MIMEText(sendfile, 'base64', 'utf-8')
- attach['Content-Type'] = 'application/octet-stream'
- attach['Content-disposition'] = 'attachment; filename ="test.txt" ' #邮件上显示的附件名称
- msgRoot = MIMEMultipart('related')
- msgRoot['Subject'] = subject
- msgRoot['test']
- msgRoot.attach(attach)
- smtp = smtplib.SMTP()
- smtp.connect(smtpserver)
- smtp.login(user, password)
- smtp.sendmail(sender, receiver, msgRoot.as_string())
- smtp.quit()
收到的邮件如下:
来源: http://www.bubuko.com/infodetail-2870528.html