Python實現各種郵件發送
前言:
Python內置對SMTP的支持,可以發送純文本郵件、HTML郵件以及帶附件的郵件。
Python對SMTP支持有smtplib和email兩個模塊,email負責構造郵件,smtplib負責發送郵件。
一、發送純文本內容
代碼如下:
# 引入相應的模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.utils import parseaddr, formataddr class SendMail(object): def __init__(self): self.fromUser = "[email protected]" self.userPasswd = "xxxxxx" # 此處是qq郵箱授權碼, 不是登錄密碼 self.smtpAddr = "smtp.qq.com" # 構造郵件結構 # toAddrs 收件人可以是多個,["[email protected]","[email protected]"], subject 郵件的主題, msg 郵件的內容 def mailStructure(self, toAddrs, subject, msg): # 郵件對象: mailMsg = MIMEMultipart() mailMsg['Subject'] = ("Hello <%s>" % subject) mailMsg['From'] = ("Python管理員 <%s>" % self.fromUser) mailMsg['To'] = ','.join(toAddrs) # 郵件正文是MIMEText : mailMsg.attach(MIMEText(msg, 'html', 'utf-8')) return mailMsg.as_string() # 發送郵件 def sendMail(self, toAddrs, subject, msg): mailMsg_as_string = self.mailStructure(toAddrs, subject, msg) # 連接服務器發送郵件 try: server = smtplib.SMTP_SSL(self.smtpAddr, 465) server.connect(self.smtpAddr) # 連接smtp服務器 server.login(self.fromUser, self.userPasswd) # 登錄郵箱 server.sendmail(self.fromUser, toAddrs, mailMsg_as_string) # 發送郵件 server.quit() except Exception: print("Error: unable to send email") a = SendMail() a.sendMail(["[email protected]", "[email protected]"], "測試主題", "測試內容")
效果圖:
二、發送附件圖片
代碼如下:
如果Email中要加上附件怎麼辦?帶附件的郵件可以看做包含若幹部分的郵件:文本和各個附件本身,所以,可以構造一個MIMEMultipart對象代表郵件本身,然後往裡面加上一個MIMEText作為郵件正文,再繼續往裡面加上表示附件的MIMEBase對象即可:
其實就是打開圖片並引入(加上這段內容)
with open(r"C:\Users\YJ\Desktop\favicon.png", "rb") as f: # 設置附件的MIME和文件名,這裡是png類型: mime = MIMEBase("image", "png", filename="test.png") # 加上必要的頭信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 添加到MIMEMultipart: mailMsg.attach(mime)
發送附件圖片 (完整代碼如下:)
# 引入相應的模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.utils import parseaddr, formataddr class SendMail(object): def __init__(self): self.fromUser = "[email protected]" self.userPasswd = "xxxxxx" # 此處是qq郵箱授權碼, 不是登錄密碼 self.smtpAddr = "smtp.qq.com" # 構造郵件結構 # toAddrs 收件人可以是多個,["[email protected]","[email protected]"], subject 郵件的主題, msg 郵件的內容 def mailStructure(self, toAddrs, subject, msg): # 郵件對象: mailMsg = MIMEMultipart() mailMsg['Subject'] = ("Hello <%s>" % subject) mailMsg['From'] = ("Python管理員 <%s>" % self.fromUser) mailMsg['To'] = ','.join(toAddrs) # 郵件正文是MIMEText : mailMsg.attach(MIMEText(msg, 'html', 'utf-8')) # 發送圖片附件, 需要用到附件對象MIMEBase對象, 需要引入from email.mime.multipart import MIMEBase # 添加附件就是加上一個MIMEBase,從本地讀取一個圖片: with open(r"C:\Users\YJ\Desktop\favicon.png", "rb") as f: # 設置附件的MIME和文件名,這裡是png類型: mime = MIMEBase("image", "png", filename="test.png") # 加上必要的頭信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 添加到MIMEMultipart: mailMsg.attach(mime) return mailMsg.as_string() # 發送郵件 def sendMail(self, toAddrs, subject, msg): mailMsg_as_string = self.mailStructure(toAddrs, subject, msg) # 連接服務器發送郵件 try: server = smtplib.SMTP_SSL(self.smtpAddr, 465) server.connect(self.smtpAddr) # 連接smtp服務器 server.login(self.fromUser, self.userPasswd) # 登錄郵箱 server.sendmail(self.fromUser, toAddrs, mailMsg_as_string) # 發送郵件 server.quit() except Exception: print("Error: unable to send email") a = SendMail() a.sendMail(["[email protected]", "[email protected]"], "測試主題", "測試內容")
效果圖:
如果要把一個圖片嵌入到郵件正文中怎麼做?直接在HTML郵件中鏈接圖片地址行不行?答案是,大部分郵件服務商都會自動屏蔽帶有外鏈的圖片,因為不知道這些鏈接是否指向惡意網站。
要把圖片嵌入到郵件正文中,我們隻需按照發送附件的方式,先把郵件作為附件添加進去,然後,在HTML中通過引用src="cid:0"就可以把附件作為圖片嵌入瞭。如果有多個圖片,給它們依次編號,然後引用不同的cid:x即可。
其實就是將MIMEText 格式改變一下:
mailMsg.attach(MIMEText('<html><body><h1>%s</h1>' % (msg) + '<p><img src="cid:0"></p>' + '</body></html>', 'html','utf-8'))
將附件圖片包含在郵件內容中(完整代碼如下:)
# 引入相應的模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.utils import parseaddr, formataddr class SendMail(object): def __init__(self): self.fromUser = "[email protected]" self.userPasswd = "xxxxxx" # 此處是qq郵箱授權碼, 不是登錄密碼 self.smtpAddr = "smtp.qq.com" # 構造郵件結構 # toAddrs 收件人可以是多個,["[email protected]","[email protected]"], subject 郵件的主題, msg 郵件的內容 def mailStructure(self, toAddrs, subject, msg): # 郵件對象: mailMsg = MIMEMultipart() mailMsg['Subject'] = ("Hello <%s>" % subject) mailMsg['From'] = ("Python管理員 <%s>" % self.fromUser) mailMsg['To'] = ','.join(toAddrs) # 郵件正文是MIMEText : # 加載圖片並引入到郵件內容中來 mailMsg.attach(MIMEText('<html><body><h1>%s</h1>' % (msg) + '<p><img src="cid:0"></p>' + '</body></html>', 'html','utf-8')) # 發送圖片附件, 需要用到附件對象MIMEBase對象, 需要引入from email.mime.multipart import MIMEBase # 添加附件就是加上一個MIMEBase,從本地讀取一個圖片: with open(r"C:\Users\YJ\Desktop\favicon.png", "rb") as f: # 設置附件的MIME和文件名,這裡是png類型: mime = MIMEBase("image", "png", filename="test.png") # 加上必要的頭信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 添加到MIMEMultipart: mailMsg.attach(mime) return mailMsg.as_string() # 發送郵件 def sendMail(self, toAddrs, subject, msg): mailMsg_as_string = self.mailStructure(toAddrs, subject, msg) # 連接服務器發送郵件 try: server = smtplib.SMTP_SSL(self.smtpAddr, 465) server.connect(self.smtpAddr) # 連接smtp服務器 server.login(self.fromUser, self.userPasswd) # 登錄郵箱 server.sendmail(self.fromUser, toAddrs, mailMsg_as_string) # 發送郵件 server.quit() except Exception: print("Error: unable to send email") a = SendMail() a.sendMail(["[email protected]", "[email protected]"], "測試主題", "測試內容")
效果圖:
三、發送純文本附件
代碼如下:
# 引入相應的模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.utils import parseaddr, formataddr class SendMail(object): def __init__(self): self.fromUser = "[email protected]" self.userPasswd = "xxxxxx" # 此處是qq郵箱授權碼, 不是登錄密碼 self.smtpAddr = "smtp.qq.com" # 構造郵件結構 # toAddrs 收件人可以是多個,["[email protected]","[email protected]"], subject 郵件的主題, msg 郵件的內容 def mailStructure(self, toAddrs, subject, msg): # 郵件對象: mailMsg = MIMEMultipart() mailMsg['Subject'] = ("Hello <%s>" % subject) mailMsg['From'] = ("Python管理員 <%s>" % self.fromUser) mailMsg['To'] = ','.join(toAddrs) # 郵件正文是MIMEText : mailMsg.attach(MIMEText(msg, 'html', 'utf-8')) # 發送文件附件, 需要用到附件對象MIMEBase對象, 需要引入from email.mime.multipart import MIMEBase # 添加附件就是加上一個MIMEBase,從本地讀取一個文件: with open(r"C:\Users\YJ\Desktop\aaa.txt", "rb") as f: # 設置附件的MIME和文件名,這裡是png類型: mime = MIMEBase("txta", "txt", filename="test.txt") # 加上必要的頭信息: mime.add_header('Content-Disposition', 'attachment', filename='test.txt') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 添加到MIMEMultipart: mailMsg.attach(mime) return mailMsg.as_string() # 發送郵件 def sendMail(self, toAddrs, subject, msg): mailMsg_as_string = self.mailStructure(toAddrs, subject, msg) # 連接服務器發送郵件 try: server = smtplib.SMTP_SSL(self.smtpAddr, 465) server.connect(self.smtpAddr) # 連接smtp服務器 server.login(self.fromUser, self.userPasswd) # 登錄郵箱 server.sendmail(self.fromUser, toAddrs, mailMsg_as_string) # 發送郵件 server.quit() except Exception: print("Error: unable to send email") a = SendMail() a.sendMail(["[email protected]", "[email protected]"], "測試主題", "測試內容")
效果圖:
四、發送excel表格附件
代碼如下:
#! /usr/bin/env python # _*_ coding: utf-8 _*_ import smtplib, time from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart class EmailSender(object): def __init__(self): self.sender_user = '[email protected]' #發件人郵箱地址 self.sender_password = 'xxxxxxxxxx' #發件人郵箱密碼 self.smtp_server_addr = 'smtp.exmail.qq.com' #smtp服務器地址 self.smtp_server_port = 465 #smtp服務器端口 def main_email(self, text, xlsx_path, xlsx_name): ''' 郵件主題,包含郵件正文 + excel 附件 Args: text:郵件正文內容 xlsx_path: excel文件路徑 xlsx_name: excel文件,例如a.xlsx Returns: 返回要發送的數據,正文和附件 ''' msg =MIMEMultipart() #添加純文本,郵件文本內容,字符串格式 text_msg = MIMEText(text, 'html', 'utf-8') msg.attach(text_msg) #將xlsx文件作為內容發送到對方的郵箱讀取excel,rb形式讀取,對於MIMEText()來說默認的編碼形式是base64 對於二進制文件來說沒有設置base64,會出現亂碼 excel_msg = MIMEText(open(xlsx_path, 'rb').read(), 'base64', 'utf-8') #設置文件再附件當中的名字 excel_msg.add_header('Content-Disposition', 'attachment', filename=('gbk', '', xlsx_name)) #添加到郵件內容msg中 msg.attach(excel_msg) return msg def login_email(self): server = smtplib.SMTP_SSL(self.smtp_server_addr, self.smtp_server_port) #連接smtp服務器 server.connect(self.smtp_server_addr) #連接smtp服務器 result = server.login(self.sender_user, self.sender_password) #登陸郵箱 print("登陸結果: ", result) return server def send_email(self, title, to_receiver, msg): ''' 發送郵件 Args: title: 郵件的主題 to_receiver: 收件人郵箱地址,可以是列表 msg: main_email函數返回的郵件主體 Returns: ''' server = self.login_email() msg['Subject'] = title msg['From'] = self.sender_user msg['To'] = ','.join(to_receiver) msg['Accept-Language']='zh-CN' msg['Accept-Charset']='ISO-8859-1,utf-8' server.sendmail(self.sender_user, to_receiver, msg.as_string()) #發送郵件 sed_mail = EmailSender() text = time.strftime('%Y-%m-%d') + "數據統計" msg = sed_mail.main_email(text, r'小程序日報V2.0(試行版).xlsx', '小程序日報.xlsx') sed_mail.send_email(title='數據統計', to_receiver=['[email protected]', '[email protected]'], msg=ms
到此這篇關於Python實現各種郵件發送的文章就介紹到這瞭,更多相關Python 發送郵件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!