Python 邮件发送
SMTP(Simple Mail Transfer Protocol,简单邮件传输协议),它是一组由源地址到目的地址传送邮件的规则,控制信件的中转方式。
python 的 smtplib 模块用于发送电子邮件。它对 smtp 协议进行了简单的封装。
import smtplib smtp = smtplib.SMTP(host, port) # 实例化对象
smtp.login(username, password) # 登录邮箱账号
smtp.sendmail(sender, receiver, msg.as_string()) # 发送邮件
email 模块主要负责构造邮件。
from email.mime.multipart import MIMEMultipart # 文本和附件 from email.mime.text import MIMEText # 文本和HTML from email.mime.image import MIMEImage # 图片
简单实例:
import smtplib from email.mime.text import MIMEText from email.header import Header host = "smtp.XXX.com" port = username = "" password = "" sender = '' receiver = [''] content = '' message = MIMEText(content, 'plain', 'utf-8') # 邮件内容,格式,编码 message['From'] = sender message['To'] = ','.join(receiver) subject = '' message['Subject'] = Header(subject, 'utf-8') # 邮件主题 try: smtpObj = smtplib.SMTP(host, port) smtpObj.login(username,password) smtpObj.sendmail(sender, receiver, message.as_string()) print("邮件发送成功") smtpObj.quit() except smtplib.SMTPException: print("邮件发送失败")
MIMEText 文本格式:plain / html 。