手把手教你使用python发送邮件
前言
发送电子邮件是个很常见的开发需求。平时如果有什么重要的信息怕错过,,就可以发个邮件到邮箱来提醒自己。
使用 Python 脚本发送邮件并不复杂。不过由于各家邮件的发送机制和安全策略不同,常常会因为一些配置问题造成发送失败。今天我们来举例讲讲如何使用 Python 发送邮件。
发送多附件邮件
该代码支持多附件发送
Python发送多附件邮件的基本思路,首先就是用MIMEMultipart()方法来表示这个邮件由多个部分组成。然后再通过attach()方法将各部分内容分别加入到MIMEMultipart容器中。MIMEMultipart有attach()方法,而MIMENouMultipart没有,只能被attach。
#!/usr/bin/env python
# -*- coding:utf-8 -*-import os
import smtplib
from email.utils import parseaddr
from email.utils import formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplicationdef send_email():'''smtp服务器 按需填写qq邮箱: smtp.qq.com126 邮箱: smtp.126.com163 邮箱: smtp.163.com'''host_server = 'smtp.qq.com' sender = 'xxxxx@qq.com' # 发件人邮箱code = 'xxxxxx' # 授权码user = 'xxxxxx@163.com' # 收件人邮箱# 邮件信息mail_title = '标题' # 标题mail_content = '请查看附件' # 邮件正文内容senderName = "发件人名称"msg = MIMEText(mail_content, _subtype='plain', _charset='utf-8')# 格式处理 (防止中文内容邮件会显示乱码)msg['Accept-Language'] = 'zh-CN'msg['Accept-Charset'] = 'ISO-8859-1,utf-8'# 首先用MIMEMultipart()来标识这个邮件由多个部分组成msgAtt = MIMEMultipart()msgAtt.attach(msg)mailAttachment = [r"C:\Users\PC\Desktop\文本.txt", r"C:\Users\PC\Desktop\excel文件.xlsx", r"C:\Users\PC\Desktop\图片.png"]for i in mailAttachment:'''MIME有很多种类型,如果附件是文本格式,就是MIMEText;如果是图片格式就行MIMEImage;如果是音频格式就用MIMEAudio,如果是其他类型的格式例如pad,word、Excel等类型的,就很难确定用那种MIME了,此时可以使用MIMEApplication()方法。MIMEApplication默认子类型是application/octet-stream,表明“这是个二进制,不知道文件的下载类型”,客户端收到这个声明后,根据文件后的扩展名进行处理。'''# 通过MIMEApplication构造附件att = MIMEApplication(open(i, 'rb').read())att["Content-Type"] = 'application/octet-stream'att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(i))msgAtt.attach(att)msg = msgAtt# ----------------------- 以下为单个附件 -----------------------# # 构造附件# mailAttachment = r"C:\Users\50234\Desktop\测试文件\透视表.xlsx"# att = MIMEApplication(open(mailAttachment, 'rb').read())# att["Content-Type"] = 'application/octet-stream'# att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(mailAttachment))# msgAtt.attach(att)# msg = msgAttmsg['Subject'] = mail_title # 邮件主题msg['From'] = formataddr(pair=(senderName, sender)) # 发件人和发件人名称msg['To'] = user# SMTPsmtp = smtplib.SMTP(host_server)# 登录--发送者账号和口令smtp.login(sender, code)# 发送邮件smtp.sendmail(sender, user, msg.as_string())# 退出smtp.quit()if __name__ == '__main__':send_email()
运行后,对应的测试结果如下:

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
