前言:python邮件发送相关
python使用第三方 SMTP 服务发送邮件
使用126邮箱,需要先注册后开启IMAP/SMTP服务,得到16位授权码
import smtplib
from email import message
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP服务
mail_host = "smtp.126.com" # 服务器名
mail_user = 'xxx' # 邮箱名
mail_pass = 'xxxxxxxxxxxxxxxx' # 开启IMAP/SMTP服务第三方授权密码(16位)
mail_postfix = '126.com' # 邮箱后缀
send_adress = mail_user + "@" + mail_postfix # 发送地址
sender = mail_user + "<" + send_adress + ">" # 昵称<邮箱地址>
receivers = ['xxx@qq.com'] # 发送列表,可以给多人发送
message = MIMEText('python 邮件发送测试', 'plain', 'utf-8') # 发送内容
message['from'] = send_adress
message['to'] = ';'.join(receivers)
subject = 'python smtp邮件测试' # 邮件主题
message['subject'] = subject
# print(message.as_string())
try:
smtpObj = smtplib.SMTP(mail_host, 25) # 非SSL协议发送
# smtpObj = smtplib.SMTP_SSL(mail_host, 465) # SSL协议发送
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
except smtplib.SMTPConnectError:
print('smtp connect error')
except smtplib.SMTPAuthenticationError:
print('smtp login error')
except smtplib.SMTPException as e:
print(type(e))
print('send error')
python发送带附件邮件
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送
import os
import smtplib
from email import message
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 第三方 SMTP服务
mail_host = "smtp.126.com" # 服务器名
mail_user = 'xxx' # 邮箱名
mail_pass = 'XXXXXXXXXXXXXXXX' # 开启IMAP/SMTP服务第三方授权密码(16位)
mail_postfix = '126.com' # 邮箱后缀
send_adress = mail_user + "@" + mail_postfix # 发送地址
sender = mail_user + "<" + send_adress + ">" # 昵称<邮箱地址>
# 发送者一般很少改动,添加接收者情况较多
receiver_list = ['xxx@qq.com', 'xxx@hotmail.com'] # 发送列表,可以给多人发送
# 创建一个带附件的邮件实例
message = MIMEMultipart()
content = 'python 邮件发送测试' # 内容可更改
msg_content = MIMEText(content, 'plain', 'utf-8') # 发送内容
message.attach(msg_content)
# 添加发送者、接收者、主题
message.add_header('from', send_adress)
receivers = ';'.join(receiver_list)
message.add_header('to', receivers)
subject = 'python smtp邮件测试' # 邮件主题可更改
message.add_header('subject', subject)
# 构造附件1,传送当前目录下的 test.txt 文件。可以类似添加多个附件
file_addr = '126.tif' # 待添加附件地址,可更改
att1 = MIMEText(open(file_addr, 'rb').read(), 'base64', 'utf-8')
att1.add_header('Content-Type', 'application/octet-stream')
file_name =os.path.basename(file_addr) # 附件名,也可自定义名称,可更改
att1.add_header('content-disposition', 'attachment', filename=file_name)
message.attach(att1)
# print(message.as_string())
try:
smtpObj = smtplib.SMTP(mail_host, 25) # 非SSL协议发送
# smtpObj = smtplib.SMTP_SSL(mail_host, 465) # SSL协议发送
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receiver_list, message.as_string())
except smtplib.SMTPConnectError:
print('smtp connect error')
except smtplib.SMTPAuthenticationError:
print('smtp login error')
except smtplib.SMTPException as e:
print(type(e))
print('send error')
使用Python发送HTML格式的邮件
Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html
注:在 HTML 文本中添加图片,邮件的 HTML 文本中一般邮件服务商添加外链是无效的。需要时查