博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python - 发送邮件
阅读量:5772 次
发布时间:2019-06-18

本文共 4451 字,大约阅读时间需要 14 分钟。

0. 邮件知识介绍

  

Content-Type: text/plain; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitTo: jinguang.liu@qq.comFrom: jliu@163.comSubject: This is a test emailDate: Wed, 22 Apr 2015 22:26:32 +0800Message-ID: <20150422142632.10808.43927@bob-PC>  Hello,   this is an autotest email.---anonimous

 

 

  SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本、HTML、带附件的邮件

  发送邮件用到Python的两个模块 email 和 smtplib,其中email用于构造邮件,而smtplib负责发送邮件

  下面我们分别介绍Python通过第三方SMTP服务器分别发送纯文本、HTML、带附件的邮件

1. 发送纯文本邮件

  Header对象用于对邮件中的字符串进行编码

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptiondef send_mail():    # 第三方SMTP邮件服务器信息    # SMTP发件服务器地址    mail_host = 'smtp.exmail.qq.com'    # 登录SMT服务器的用户名    mail_user = 'xx@xx.com'    # 登录SMTP服务器的密码,对于126、163邮箱,此处是授权密码而不是登录密码    mail_pass = 'xxxx'    # 发送人    sender = 'xx@xx.com'    # 接收邮件地址,可以填写多个地址    receivers = ['mail1@126.com', 'mail2@qq.com']    # 邮件正文    content = 'Hello World!'      # 通过MIMETEXT对象构造邮件,参数分别为邮件内容,邮件MIMETYPE,字符集    msg = MIMEText(content, 'plain', 'utf-8')    # 邮件标题栏显示的发件人    msg['From'] = Header(sender, 'utf-8')    # 邮件标题栏处显示的收件人    msg['To'] = Header(','.join(receivers), 'utf-8')    # 邮件标题    msg['Subject'] = Header('Python Test', 'utf-8')    # 发送邮件    try:        # 通过SMTP对象负责发送邮件,参数分别为SMTP服务器地址,SMTP服务器监听的端口号,        # 此处可以使用非加密(SMTP)或加密(SMTP_SSL)方式进行传输, 非加密默认监听端口号为25,加密为465        # smtp_obj = SMTP(mail_host, 25)        smtp_obj = SMTP_SSL(mail_host, 465)        # 登录        smtp_obj.login(mail_user, mail_pass)        # 发送邮件        smtp_obj.sendmail(sender, receivers, msg.as_string())        smtp_obj.quit()        print('Send mail successful')    except SMTPException:        print('Email failed to send')if __name__ == '__main__': send_mail()

 

 

  网易邮箱通过下图所示的设置,授权第三方应用程序通过其发送邮件

  

   

 

2. 发送HTML邮件

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptiondef send_mail():    mail_host = 'smtp.exmail.qq.com'    mail_user = 'zhueb@nianqa.com'    mail_pass = 'xxxx'    sender = 'zhueb@nianqa.com'    receivers = ['zhubiaook@126.com', '1003685280@qq.com']    content = """            

Welcome to my site

https://www.cnblogs.com/zhubiao """    # 将MIME类型修改为html即可 msg = MIMEText(content, 'html', 'utf-8') msg['From'] = Header(sender, 'utf-8') msg['To'] = Header(','.join(receivers), 'utf-8') msg['Subject'] = Header('Python Test', 'utf-8') # 发送邮件 try: # smtp_obj = SMTP(mail_host, 25) smtp_obj = SMTP_SSL(mail_host, 465) smtp_obj.login(mail_user, mail_pass) smtp_obj.sendmail(sender, ','.join(receivers), msg.as_string()) smtp_obj.quit() print('Email sent successfully') except SMTPException: print('Email failed to send')if __name__ == '__main__': send_mail()

 

3. 发送带附件的邮件

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptionfrom email.mime.multipart import MIMEMultipartdef send_mail():    # 第三方SMTP服务器连接信息    mail_host = 'smtp.exmail.qq.com'    mail_user = 'zhueb@nianqa.com'    mail_pass = 'xxxx'    sender = 'zhueb@nianqa.com'    receivers = ['zhubiaook@126.com', '1003685280@qq.com']    # 创建MIMEMultipart对象,可包含text、image、html等混合类型    msg = MIMEMultipart()    # 邮件首部    msg['From'] = Header(sender, 'utf-8')    msg['To'] = Header(','.join(receivers), 'utf-8')    msg['Subject'] = Header('Python Mail Test', 'utf-8')    # 邮件正文内容    # 邮件正文为html, 插入一张图片,图片来自于附件,其中cid:value表示附件首部键值对Content-ID : value.    content = """        
""" msg_content = MIMEText(content, 'html', 'utf-8') msg.attach(msg_content) for file in ['test.xlsx', 'img1.jpg', 'img2.jpg']: # 附件1 with open(file, 'rb') as fp: att = MIMEText(fp.read(), 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = 'attachment; filename= "test.xlsx"' att['Content-ID'] = file msg.attach(att) # 发送邮件 try: # smtp_obj = SMTP(mail_host, 25) smtp_obj = SMTP_SSL(mail_host, 465) smtp_obj.login(mail_user, mail_pass) smtp_obj.sendmail(sender, ','.join(receivers), msg.as_string()) smtp_obj.quit() print('Email sent successfully') except SMTPException: print('Email failed to send')if __name__ == '__main__': send_mail()

 

 4. Python发送短信

 

 

转载于:https://www.cnblogs.com/zhubiao/p/9363260.html

你可能感兴趣的文章
logback指定日志存放位置
查看>>
html5离线Web应用程序介绍
查看>>
python实现中文输出的两种方法
查看>>
Python OS模块
查看>>
OPENCC linux安装(php_opencc.so编译)
查看>>
Python URL中文的编解码
查看>>
centos安装msmtp,利用gmail发送
查看>>
asp.net application life cycle
查看>>
Spark的性能调优
查看>>
入职新人技术引导之我见
查看>>
linux下mongo启动关闭重启方法
查看>>
一些网站
查看>>
语音特征参数MFCC提取过程详解
查看>>
使用GitHub进行版本管理
查看>>
如何选择适合你的渲染软件
查看>>
c++动态规划解决硬币换零钱的问题
查看>>
Qt下几个线程函数介绍
查看>>
Passware Kit和AOPR哪个更厉害?
查看>>
Loading XML with Javascript
查看>>
C++、Java、JavaScript中迭代器的用法
查看>>