使用Python3发送邮件测试代码
生活随笔
收集整理的這篇文章主要介紹了
使用Python3发送邮件测试代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SMTP(Simple Mail Trasfer Protocol)即簡單郵件傳輸協(xié)議,它是一組用于由源地址到目的地址傳送郵件的規(guī)則,用它來控制信件的中轉方式。Python3對SMTP的支持有smtplib和email兩個模塊,smtplib負責發(fā)送電子郵件, email負責組織郵件內容,可發(fā)送的郵件形式包括:純文本文件、html、附件、圖像。
下面的測試代碼是以給163發(fā)送郵件為例,獲取163的授權碼方式可以參考:https://jingyan.baidu.com/article/ce09321b862ed12bff858fd9.html
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header# reference: http://www.runoob.com/python/python-email.html# 第三方SMTP服務, 如163, qq, sina
mail_host = "smtp.163.com" # 設置服務器
mail_port = 25 # 端口號
mail_user = "fengbingchun" # 用戶名
mail_pass = "xxxxx" # 163授權碼sender = "fengbingchun@163.com" # 發(fā)送方
receivers = ["fengbingchun@163.com"] # 接收方def SendTextMessage(text):''' 發(fā)送純文本郵件, text: 郵件內容 ''' # 三個參數:第一個為文本內容,第二個plain設置文本格式,第三個utf-8設置編碼message = MIMEText(text, 'plain', 'utf-8') # 郵件內容message['From'] = Header("菜鳥教程", 'utf-8') # 發(fā)送者message['To'] = Header("測試", 'utf-8') # 接收者subject = 'Python SMTP 郵件測試: plain text' # 郵件主題message['Subject'] = Header(subject, 'utf-8')try:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, mail_port)smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string())print("郵件發(fā)送成功: plain text")except smtplib.SMTPException:print("Error: 無法發(fā)送郵件, plain text")def SendHtmlMessage():''' 發(fā)送html郵件 '''mail_msg = """<p>Python 郵件發(fā)送測試: this is a html email</p><p><a href="http://www.runoob.com">這是一個鏈接</a></p>"""message = MIMEText(mail_msg, 'html', 'utf-8')message['From'] = Header("菜鳥教程", 'utf-8')message['To'] = Header("測試", 'utf-8')subject = 'Python SMTP 郵件測試: html'message['Subject'] = Header(subject, 'utf-8')try:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, mail_port)smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string())print("郵件發(fā)送成功: html")except smtplib.SMTPException:print("Error: 無法發(fā)送郵件, html")def SendAttachmentMessage():''' 發(fā)送帶附件的郵件 '''message = MIMEMultipart()message['From'] = Header("菜鳥教程", 'utf-8')message['To'] = Header("測試", 'utf-8')subject = 'Python SMTP 郵件測試: attachment'message['Subject'] = Header(subject, 'utf-8')# 郵件正文內容message.attach(MIMEText('這是菜鳥教程Python 郵件發(fā)送測試: attachment', 'plain', 'utf-8'))# 構造附件1,傳送當前目錄下的 test.txt 文件att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')att1["Content-Type"] = 'application/octet-stream'# 這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字att1["Content-Disposition"] = 'attachment; filename="test.txt"'message.attach(att1)# 構造附件2,傳送當前目錄下的 runoob.txt 文件att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')att2["Content-Type"] = 'application/octet-stream'att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'message.attach(att2)try:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, mail_port)smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string())print("郵件發(fā)送成功: attachment")except smtplib.SMTPException:print("Error: 無法發(fā)送郵件: attachment")def SendHtmlImageMessage():''' 發(fā)送帶html+image的郵件 '''msgRoot = MIMEMultipart('related')msgRoot['From'] = Header("菜鳥教程", 'utf-8')msgRoot['To'] = Header("測試", 'utf-8')subject = 'Python SMTP 郵件測試: html+image'msgRoot['Subject'] = Header(subject, 'utf-8')msgAlternative = MIMEMultipart('alternative')msgRoot.attach(msgAlternative)mail_msg = """<p>Python 郵件發(fā)送測試: html+image</p><p><a href="http://www.runoob.com">菜鳥教程鏈接</a></p><p>圖片演示:</p><p><img src="cid:image1"></p>"""msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))# 指定圖片為當前目錄fp = open('test.png', 'rb')msgImage = MIMEImage(fp.read())fp.close()# 定義圖片 ID,在 HTML 文本中引用msgImage.add_header('Content-ID', '<image1>')msgRoot.attach(msgImage)try:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, mail_port)smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, msgRoot.as_string())print("郵件發(fā)送成功: html+image")except smtplib.SMTPException:print("Error: 無法發(fā)送郵件: html+image")if __name__ == "__main__":SendTextMessage("Hello, Python 郵件發(fā)送測試: this is a plain text email!")SendHtmlMessage()SendAttachmentMessage()SendHtmlImageMessage() print("finish")
執(zhí)行結果如下:
收到的郵件結果如下:
GitHub:https://github.com/fengbingchun/Python_Test
總結
以上是生活随笔為你收集整理的使用Python3发送邮件测试代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TeamViewer介绍:远程控制计算机
- 下一篇: Ubuntu定时任务crontab命令介