1 登录认证

  1. import smtplib
  2. host = 'smtp.mail.qq.com'
  3. # smtp = smtplib.SMTP(host=host, port=smtplib.SMTP_PORT)
  4. smtp = smtplib.SMTP_SSL(host=host, port=smtplib.SMTP_SSL_PORT) # use SSL mode, recommended
  5. res = smtp.login('username', 'password')
  6. if res[0] == 235:
  7. print('login successful!')

2 发送邮件

content_type:

  • plain: 文本格式
  • html: HTML格式
  1. from email.header import Header
  2. from email.mime.text import MIMEText
  3. from email.mime.multipart import MIMEMultipart
  4. from_addr = 'your@mail.com'
  5. to_addrs = 'to@mail.com'
  6. charset = 'utf-8'
  7. content_type = 'plain' # or html
  8. body = 'your mail body'
  9. subject = 'your mail subject'
  10. msg = MIMEMultipart()
  11. msg['Subject'] = Header(subject, charset)
  12. msg['To'] = to_addrs
  13. msg.attach(MIMEText(body, content_type, charset))
  14. smtp.sendmail(from_addr, to_addrs, msg.as_string())

3 发送多人

msg[‘To’]部分为字符串,仅用于控制显示接收人 sendmail内部to_addrs列表,才能发送给多人,否则只会发送给第一个

  1. to_addrs = ['a@mail.com', 'b@mail.com', 'c@mail.com']
  2. msg['To'] = ','.join(to_addrs)
  3. ...
  4. smtp.sendmail(from_addr, to_addrs, msg.as_string())

4 抄送密送

抄送:发送者和其他接收者都知道抄送了谁 密送:只有发送者知道密送了谁 同样的,msg[‘Cc’]和msg[‘Bcc’]只是控制显示,是否真正发送,还要看实际传给sendmail的to_addrs列表

  1. cc_list = ['d@mail.com']
  2. bcc_list = ['e@mail.com']
  3. msg['Cc'] = ','.join(cc_list)
  4. msg['Bcc'] = ','.join(bcc_list)
  5. smtp.sendmail(from_addr, to_addrs + cc_list + bcc_list, msg.as_string())

5 发送附件

直接使用MIMEApplication创建附件对象即可,无需区分文件类型

  1. import os
  2. from email.mime.application import MIMEApplication
  3. msg = MIMEMultipart()
  4. ...
  5. attachments = [
  6. 'a.txt',
  7. 'b.png',
  8. 'c.mp3',
  9. 'd.mp4'
  10. ]
  11. for file in attachments:
  12. filename = os.path.basename(file)
  13. application = MIMEApplication(open(file, 'rb').read())
  14. application.add_header('Content-Disposition', 'attachment', filename=filename)
  15. msg.attach(application)
  16. smtp.sendmail(from_addr, to_addrs, msg.as_string())