SMTP是发送邮件的协议,Python内置对SMTP的支持(smtplib模块和email模块),可以发送纯文本邮件、HTML邮件以及带附件的邮件
SMTP:Simple Mail Transfer Protocol简单邮件传输协议,是从源地址到目的地址传送邮件的规则,由该协议控制信件的中转方式
python的smtplib提供了一种很方便的途径传递电子邮件,对SMTP进行了简单的封装
发送纯文本邮件
#导入smtplib模块
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
def send_email(SMTP_host, from_addr, password, to_addrs, subject, content):
email_client = SMTP(SMTP_host)
email_client.login(from_addr, password)
msg = MIMEText(content,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')#subject
msg['From'] = 'xx@163.com'
msg['To'] = "xx@qq.com"
#sendmail(邮件发送者地址,字符串列表(收件人),发送内容)
email_client.sendmail(from_addr, to_addrs, msg.as_string())
send_email("smtp.163.com","xx@163.com","password","xx@qq.com","lsllsldld","hellow")
发送HTML格式的邮件
#导入smtplib模块
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
def send_email(SMTP_host, from_addr, password, to_addrs, subject, content):
email_client = SMTP(SMTP_host)
email_client.login(from_addr, password)
#发送纯文本邮件 设置为plain,发送html邮件修改为 MIMEText(content,'html','utf-8')
msg = MIMEText(content,'html','utf-8')
msg['Subject'] = Header(subject, 'utf-8')#subject
msg['From'] = 'xx@163.com'
msg['To'] = "xx@qq.com"
#sendmail(邮件发送者地址,字符串列表(收件人),发送内容)
#发送纯文本邮件
email_client.sendmail(from_addr, to_addrs, msg.as_string())
send_email("smtp.163.com","xxx@163.com","password","xxx@qq.com","lsllsldld","<h1>sdf</h1><ul><li>2</li></ul>")
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。