# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 16:02:17 2019
@author: liuxiaohuan
"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
sender = '[email protected]'
receiver = list()#接收者列表
receiver.append('[email protected]')
copyReceive = list()#抄送者列表
copyReceive.append(sender)#将发件人添加到抄送列表
username = '[email protected]'#发件人邮箱账号
password = 'uakdghjbupowasdf'#授权密码
mailall=MIMEMultipart()
mailall['Subject'] = "凯凯是头猪" #记住一定要设置,并且要稍微正式点
mailall['From'] = sender #发件人邮箱
mailall['To'] = ';'.join(receiver) #收件人邮箱,不同收件人邮箱之间用;分割
mailall['CC'] = ';'.join(copyReceive) #抄送邮箱
mailcontent = '凯凯是头猪'
mailall.attach(MIMEText(mailcontent, 'plain', 'utf-8'))
mailAttach = '测试邮件附件内容'
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
filename = r'C:/Users/liuxiaohuan/Desktop/1.txt'#附件文件所在路径
attfile = MIMEBase(maintype, subtype)
attfile.set_payload(open(filename, 'rb').read())
attfile.add_header('Content-Disposition', 'attachment',filename=('utf-8', '', filename))#必须加上第三个参数,用于格式化输出
encoders.encode_base64(attfile)
mailall.attach(attfile)
fullmailtext = mailall.as_string()
smtp = smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver+copyReceive, fullmailtext)#发送的时候需要将收件人和抄送者全部添加到函数第二个参数里
smtp.quit()
温馨提示:当附件内容包含有中文时,会发送失败,此处报错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 800-814: ordinal not in range(128)
解决办法:添加如下代码:
from email import encoders
encoders.encode_base64(attfile)