這篇文章主要介紹了python 傳送郵件的四種方法,幫助大家更好的理解和使用python,感興趣的朋友可以瞭解下
這裡針對smtplib做了一系列封裝,可以完成以下四種場景:
傳送純文字的郵件傳送html頁面的郵件傳送帶附件檔案的郵件傳送能展示圖片的郵件以上四種場景,已經做好了二次封裝,經測試OK,使用時直接傳入對應引數即可,直接上程式碼
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
class SendEMail(object):
"""封裝傳送郵件類"""
def __init__(self, host, port, msg_from, pwd):
self.msg_from = msg_from
self.password = pwd
# 郵箱伺服器地址和埠
self.smtp_s = smtplib.SMTP_SSL(host=host, port=port)
# 傳送方郵箱賬號和授權碼
self.smtp_s.login(user=msg_from, password=pwd)
def send_text(self, to_user, content, subject, content_type='plain'):
"""
傳送文字郵件
:param to_user: 對方郵箱
:param content: 郵件正文
:param subject: 郵件主題
:param content_type: 內容格式:'plain' or 'html'
:return:
"""
msg = MIMEText(content, _subtype=content_type, _charset="utf8")
msg["From"] = self.msg_from
msg["To"] = to_user
msg["subject"] = subject
self.smtp_s.send_message(msg, from_addr=self.msg_from, to_addrs=to_user)
def send_file(self, to_user, content, subject, reports_path, filename, content_type='plain'):
"""
傳送帶檔案的郵件
:param to_user: 對方郵箱
:param content: 郵件正文
:param subject: 郵件主題
:param reports_path: 檔案路徑
:param filename: 郵件中顯示的檔名稱
:param content_type: 內容格式
"""
file_content = open(reports_path, "rb").read()
msg = MIMEMultipart()
text_msg = MIMEText(content, _subtype=content_type, _charset="utf8")
msg.attach(text_msg)
file_msg = MIMEApplication(file_content)
file_msg.add_header('content-disposition', 'attachment', filename=filename)
msg.attach(file_msg)
msg["From"] = self.msg_from
msg["To"] = to_user
msg["subject"] = subject
self.smtp_s.send_message(msg, from_addr=self.msg_from, to_addrs=to_user)
def send_img(self, to_user, subject, content, filename, content_type='html'):
'''
傳送帶圖片的郵件
:param to_user: 對方郵箱
:param subject: 郵件主題
:param content: 郵件正文
:param filename: 圖片路徑
:param content_type: 內容格式
'''
subject = subject
msg = MIMEMultipart('related')
# Html正文必須包含<img src="cid:imageid" alt="imageid" width="100%" height="100%>
content = MIMEText(content, _subtype=content_type, _charset="utf8")
msg.attach(content)
msg['Subject'] = subject
msg['From'] = self.msg_from
msg['To'] = to_user
with open(filename, "rb") as file:
data = file.read()
img = MIMEImage(img_data)
img.add_header('Content-ID', 'imageid')
msg.attach(img)
self.smtp_s.sendmail(self.msg_from, to_user, msg.as_string())