利用python发送邮件主要借助smtplib和email两个模块
- smtplib用来建立和断开与服务器连接的工作
- email模块用来设置与邮件相关的内容,如:收件人、发件人、主题
首先要登陆邮箱,勾选POP3/SMTP服务和IMAP/SMTP服务,进行授权码设置
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
# 发件人邮箱
asender = ' '
# 收件人邮箱
areceiver = ' '
# 抄送人邮箱
acc = ' '
# 邮件主题
asubject = '测试邮件'
# 发件人地址
from_addr = ' '
# 授权码
password = ' '
# 邮件设置
msg = MIMEMultipart()
msg['Subject'] = asubject
msg['to'] = areceiver
msg['Cc'] = acc
msg['from'] = '小A'
# 邮件正文
body = '测试邮件,收到即成功'
# 添加邮件正文
msg.attach(MIMEText(body,'plain','utf-8'))
# 添加附件
xlsxpart = MIMEApplication(open('/Users/faye/Desktop/order-14.1.csv','rb').read())
xlsxpart.add_header('Content-Disposition','attachment',filename = '附件.csv')
msg.attach(xlsxpart)
# 设置邮箱服务器地址及端口
smtp_server = 'smtp.qq.com'
server = smtplib.SMTP(smtp_server,25)
server.set_debuglevel(1)
# 登陆邮箱
server.login(from_addr,password)
# 发送邮件
server.sendmail(from_addr,areceiver.split(',') + acc.split(','),
msg.as_string())
# 断开服务器连接
server.quit()