一、什么是SMTP
SMTP 是 Simple Mail Transfer Protocol(简单邮件传输协议)的缩写,是用于发送邮件的协议。Python 提供了 smtplib 模块,它对 SMTP 协议进行了封装,可以很方便地发送邮件。
二、SMTP的原理
SMTP 协议是基于文本的,它的每条命令都是一行文本,以 CR-LF(回车和换行)结尾。在 Python 中,可以使用 smtplib 模块的 SMTP 类来创建一个 SMTP 连接,然后发送邮件。
import smtplib from email.mime.text import MIMEText mail_host = "smtp.163.com" # 邮箱服务器地址 mail_user = "your_email_address" # 邮箱账号 mail_pass = "your_email_password" # 邮箱密码 sender = "your_email_address" # 发件人邮箱 receiver = "receiver_email_address" # 收件人邮箱列表 # 邮件内容 msg = MIMEText("邮件内容") msg['Subject'] = "邮件主题" msg['from'] = sender msg['to'] = ','.join(receiver) # 创建一个 SMTP 连接 smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj.login(mail_user, mail_pass) # 发送邮件 smtpObj.sendmail(sender, receiver, msg.as_string()) smtpObj.quit()
三、使用SMTP发送携带附件的邮件
在有些情况下,我们需要发送携带附件的邮件。可以使用 email.mime.multipart 模块的 MIMEMultipart 类来组合邮件内容,并添加附件。
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication mail_host = "smtp.163.com" # 邮箱服务器地址 mail_user = "your_email_address" # 邮箱账号 mail_pass = "your_email_password" # 邮箱密码 sender = "your_email_address" # 发件人邮箱 receiver = "receiver_email_address" # 收件人邮箱列表 # 组合邮件内容 msg = MIMEMultipart() msg['Subject'] = "邮件主题" msg['from'] = sender msg['to'] = ','.join(receiver) # 添加文本内容 body = "邮件正文" msg.attach(MIMEText(body, 'plain', 'utf-8')) # 添加附件 filename = "test.txt" part = MIMEApplication(open(filename,'rb').read(), Name=filename) part['Content-Disposition'] = 'attachment; filename="%s"' % filename msg.attach(part) # 创建一个 SMTP 连接 smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj.login(mail_user, mail_pass) # 发送邮件 smtpObj.sendmail(sender, receiver, msg.as_string()) smtpObj.quit()
四、使用SMTP发送HTML格式邮件
有时候我们需要发送 HTML 格式的邮件,可以使用 email.mime.text 模块的 MIMEText 类来设置 HTML 格式的邮件内容。
import smtplib from email.mime.text import MIMEText mail_host = "smtp.163.com" # 邮箱服务器地址 mail_user = "your_email_address" # 邮箱账号 mail_pass = "your_email_password" # 邮箱密码 sender = "your_email_address" # 发件人邮箱 receiver = "receiver_email_address" # 收件人邮箱列表 # 邮件内容 msg = MIMEText("这是一封 HTML 格式的电子邮件
百度", "html", "utf-8") msg['Subject'] = "邮件主题" msg['from'] = sender msg['to'] = ','.join(receiver) # 创建一个 SMTP 连接 smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj.login(mail_user, mail_pass) # 发送邮件 smtpObj.sendmail(sender, receiver, msg.as_string()) smtpObj.quit()
五、SMTP发送带图片的邮件
如果我们需要在邮件中插入图片,可以使用 email.mime.multipart 模块的 MIMEMultipart 类来组合邮件内容并添加图片。
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage mail_host = "smtp.163.com" # 邮箱服务器地址 mail_user = "your_email_address" # 邮箱账号 mail_pass = "your_email_password" # 邮箱密码 sender = "your_email_address" # 发件人邮箱 receiver = "receiver_email_address" # 收件人邮箱列表 # 组合邮件内容 msg = MIMEMultipart() msg['Subject'] = "邮件主题" msg['from'] = sender msg['to'] = ','.join(receiver) # 添加HTML内容 html = "这是一封包含图片的邮件