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()
收到的邮件如下: