日常笔记,怕时间长了忘掉,在此做以记录,有需要的小伙伴可以拿去用~
import os
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
from email.mime.text import MIMEText
recv = [''] # 收件人邮箱,多个可使用逗号分隔
send_username = '' # 发件人邮箱
passwd = '' # 授权码
smtp_server = '' # 协议地址
def send_mail(send_username, passwd, recv, title, content, mail_host, port, files=None):
'''
:param send_username: 邮箱账号
:param passwd: 邮箱密码
:param recv: 邮箱接收人地址,多个账号以逗号隔开
:param title: 邮件标题
:param content: 邮件内容
:param mail_host: 邮箱服务器
:param port: 端口号
:return:
'''
if files:
msg = MIMEMultipart()
# 构建正文
part_text = MIMEText(content)
msg.attach(part_text) # 把正文加到邮件体里面去
# 构建邮件附件
part_attach1 = MIMEApplication(open(files, 'rb').read()) # 打开附件
file_name=os.path.basename(files)
part_attach1.add_header('Content-Disposition', 'attachment', filename=file_name) # 为附件命名
msg.attach(part_attach1) # 添加附件
else:
msg = MIMEText(content) # 邮件内容
msg['Subject'] = title # 邮件主题
msg['From'] = send_username # 发送者账号
msg['To'] = ','.join(recv) # 接收者账号列表,列表要转成,隔开的字符串
# smtp = smtplib.SMTP(mail_host)
smtp = smtplib.SMTP_SSL(mail_host)
smtp.connect(mail_host,port)
smtp.login(send_username, passwd) # 登录
smtp.ehlo()
smtp.sendmail(send_username, recv, msg.as_string())
smtp.quit()
send_mail(send_username, passwd, recv, '测试', '你好你好', smtp_server,
465, files=r"C:\Users\Administrator\Desktop\test.xlsx")