导入模块


  1. import smtplib
  2. from email.mime.text import MIMEText
  3. from email.header import Header
  4. from email.mime.multipart import MIMEMultipart

创建邮箱对象


  1. Email = smtplib.SMTP()

连接服务器


  1. Email.connect('smtp.qq.com', 25)

登录邮箱


  1. Email.login('weicreate@qq.com', input('邮箱授权码:'))

添加正文


  1. content = MIMEText(input('请输入邮件内容:'), 'plain', 'utf-8')

添加附件


  1. file = MIMEText(open('excel.xlsx').read(), 'base64', 'utf-8')
  2. file.add_header('Content-Disposition', 'attachment', filename='excel.xlsx')

创建复合邮件对象


  1. msg = MIMEMultipart()
  2. msg.attach(content)
  3. msg.attach(file)

添加表头


  1. msg['From'] = Header('weicreate')
  2. obj = ['阿浩', ]
  3. msg['To'] = Header(",".join(obj))
  4. msg['Subject'] = Header('来自python的程序测试')

发送邮件


  1. objMail = ['1243007569@qq.com', ]
  2. try:
  3. Email.sendmail('weicreate@qq.com', objMail, msg.as_string())
  4. print('发送成功!')
  5. except Exception as e:
  6. print('发送失败:', repr(e))
  7. Email.quit()

参考文件


smtplib模块.py