1 登录认证
import smtplibhost = 'smtp.mail.qq.com'# smtp = smtplib.SMTP(host=host, port=smtplib.SMTP_PORT)smtp = smtplib.SMTP_SSL(host=host, port=smtplib.SMTP_SSL_PORT) # use SSL mode, recommendedres = smtp.login('username', 'password')if res[0] == 235:print('login successful!')
2 发送邮件
content_type:
- plain: 文本格式
- html: HTML格式
from email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom_addr = 'your@mail.com'to_addrs = 'to@mail.com'charset = 'utf-8'content_type = 'plain' # or htmlbody = 'your mail body'subject = 'your mail subject'msg = MIMEMultipart()msg['Subject'] = Header(subject, charset)msg['To'] = to_addrsmsg.attach(MIMEText(body, content_type, charset))smtp.sendmail(from_addr, to_addrs, msg.as_string())
3 发送多人
msg[‘To’]部分为字符串,仅用于控制显示接收人 sendmail内部
to_addrs为列表,才能发送给多人,否则只会发送给第一个
to_addrs = ['a@mail.com', 'b@mail.com', 'c@mail.com']msg['To'] = ','.join(to_addrs)...smtp.sendmail(from_addr, to_addrs, msg.as_string())
4 抄送密送
抄送:发送者和其他接收者都知道抄送了谁 密送:只有发送者知道密送了谁 同样的,msg[‘Cc’]和msg[‘Bcc’]只是控制显示,是否真正发送,还要看实际传给sendmail的to_addrs列表
cc_list = ['d@mail.com']bcc_list = ['e@mail.com']msg['Cc'] = ','.join(cc_list)msg['Bcc'] = ','.join(bcc_list)smtp.sendmail(from_addr, to_addrs + cc_list + bcc_list, msg.as_string())
5 发送附件
直接使用
MIMEApplication创建附件对象即可,无需区分文件类型
import osfrom email.mime.application import MIMEApplicationmsg = MIMEMultipart()...attachments = ['a.txt','b.png','c.mp3','d.mp4']for file in attachments:filename = os.path.basename(file)application = MIMEApplication(open(file, 'rb').read())application.add_header('Content-Disposition', 'attachment', filename=filename)msg.attach(application)smtp.sendmail(from_addr, to_addrs, msg.as_string())
