SMTP(Simple Mail Transfer Protocol)是简单传输协议,它是一组用于用于由源地址到目的地址的邮件传输规则。
python中对SMTP进行了简单的封装,可以发送纯文本邮件、HTML邮件以及带附件的邮件。核心模块:
email模块:负责构建邮件
smtplib模块:负责发送邮件
实例:
import smtplib
import time
from email.header import Header # 设置标题字符集
from email.mime.multipart import MIMEMultipart # 带多个部分的邮件
from email.mime.text import MIMEText # html格式和文本格式邮件
from email.utils import formataddr # 分隔标题与地址
from email.mime.image import MIMEImage # 带图片格式邮件
from email.mime.audio import MIMEAudio # 音频文件对象
from email.mime.application import MIMEApplication # 主要类型的MIME消息对象应用
from email import encoders # 编码器
from email.mime.base import MIMEBase
SSL = True # 如果SSL为真,使用SSL方式发送邮件,为假,不使用SSL
SMTP_PORT_SSL = 465 # 邮箱发送SSL端口
SMTP_PORT = 25 # 邮箱发送端口
SMTP_SERVER = 'smtp server' # 邮箱SMTP服务器
USER_EMAIL = 'Email' # 发送所使用的邮箱账号
USER_NAME = 'Name' # 发件人名称
PASSWORD_EMAIL = 'Password' # 邮箱密码
def send_email(title, email, text): # 邮件标题,收件人,邮件内容
if title == '':
print('请输入邮件标题')
elif email == '':
print('请输入收件人邮箱')
elif text == '':
print('请输入邮件内容')
else:
sender_email = USER_EMAIL
receiver_email = email # 收件人邮箱
subject = title # 发送的标题
subject = Header(subject, 'utf-8').encode()
# 构造邮件对像MIMEMultipart对象
msg = MIMEMultipart('mixed')
msg['Subject'] = subject # 邮件的标题
msg['From'] = formataddr([USER_NAME, USER_EMAIL]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = email
text_plain = MIMEText(text, 'html', 'utf-8') # 邮件内容为HTML超文本
msg.attach(text_plain)
# 构建HTML格式邮件带图片内容
# 添加的图片src必须是cid:xxx的形式,如:cid:image1,第二个图片就如cid:image2
html1 = "<div><img src='cid:imgid'></div>"
msg_html_img = MIMEText(html1, 'html', 'utf-8')
msg.attach(msg_html_img)
with open('p.png', 'rb') as f: # 打开图片
msg_img = MIMEImage(f.read()) # 读入图片
msg_img.add_header('Content-ID', 'imgid') # 扩展图片标题
msg.attach(msg_img) # 添加到内容
# 带附件的邮件MIMEApplication
# filename='file.docx'
# with open(filename, 'rb') as f: # 打开附件
# attachfile = MIMEApplication(f.read()) # 读入附件
# attachfile.add_header('Content-Disposition', 'attachment', filename=filename) # 扩展附件标题
# msg.attach(attachfile) # 添加附件到内容
# 带多个附件的邮件MIMEApplication
filenames = ['file.docx', 'file2.docx']
for filename in filenames:
with open(filename, 'rb') as f:
attachfiles = MIMEApplication(f.read())
attachfiles.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachfiles)
# 发送邮件
if SSL:
smtp = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT_SSL) # SSL连接
PORT = SMTP_PORT_SSL
else:
smtp = smtplib.SMTP() # 普通连接
PORT = SMTP_PORT
try:
smtp.connect(SMTP_SERVER, PORT) # 连接邮件服务器
smtp.login(USER_EMAIL, PASSWORD_EMAIL) # 验证发件人账号密码
smtp.sendmail(sender_email, receiver_email, msg.as_string()) # 发送邮件
smtp.quit() # 退出SMTP
print(time.strftime('%Y-%m-%d %H:%M:%S'), '邮件发送完成')
except smtplib.SMTPConnectError as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:连接失败: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:认证失败: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:发件人被拒绝: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:收件人被拒绝: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:数据接收拒绝: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:邮件发送失败: ', e.message)
except Exception as e:
print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Error:邮件发送异常: ', str(e))
if __name__ == '__main__':
send_email('测试邮件标题', 'xxxxx@xxx.com', '<b>测试邮件内容</b>')