Python中发送邮件主要使用到的模块:
- SMTP模块:邮件传输协议。
- email模块(主要用来定义邮件的标题和正文,Header()方法用来定义邮件的标题;MIMEText()用于定义邮件的正文)。
通过QQ邮箱发送到163邮箱。
'''发送html的邮件'''
from email.mime.text import MIMEText
from email.header import Header
import smtplib
# 发送邮箱账户
user = '*********@qq.com'
# user = '*********@163.com'
# 授权码
password = '*********'
# 发送邮箱
send = '*********@qq.com'
# 发送邮箱主题
subject = "这是邮件主题。"
# 邮箱正文
content = '这是邮件内容。'
msg = MIMEText(content, 'html', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 接收邮箱
receive = "*********.com"
# receive = "*********@163.com"
# receive = "*********@qq.com"
try:
# 连接服务器发送邮件
smt = smtplib.SMTP('smtp.qq.com')
# 向SMTP服务器确认你的身份
smt.helo()
# 向ESMTP(SMTP扩展)确认你的身份
smt.ehlo()
# 启动安全传输
# smt.starttls()
# 连接
# smt.connect(Smt_Srver)
smt.login(user, password)
smt.sendmail(send, receive, msg.as_string())
print('发送成功')
smt.quit()
except Exception as e:
print('发送失败:', e)
发送带附件的邮箱。
'''发送带附件的邮件'''
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
send_user = '********@qq.com'
send_password = '********'
send_subject = '带附件的邮件'
send_file = open(r'D:\学习笔记\Pycharm_Code\Selenium_Test\Test_12_01\Test_1230_07_txtData', 'rb').read()
msg = MIMEText(send_file, 'base64', 'utf - 8')
# 邮件内容
msg['Content-Type'] = 'application/octet-stream'
msg['Content-Disposition'] = 'attachment;filename="Test_1230_07_txtData"'
# 创建一个带附件的实例
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = send_subject
msgRoot.attach(msg)
sendUser = '********@qq.com'
receive = '********@163.com'
# receive = '********@163.com'
try:
smt = smtplib.SMTP('smtp.qq.com')
smt.ehlo()
smt.starttls()
smt.login(send_user, send_password)
smt.sendmail(sendUser, receive, msgRoot.as_string())
smt.quit()
print('发送成功')
except Exception as e:
print('发送失败', e)