国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python 發(fā)送郵件的四種方法匯總

瀏覽:9日期:2022-07-03 14:07:08

這里針對smtplib做了一系列封裝,可以完成以下四種場景:

發(fā)送純文本的郵件 發(fā)送html頁面的郵件 發(fā)送帶附件文件的郵件 發(fā)送能展示圖片的郵件

以上四種場景,已經(jīng)做好了二次封裝,經(jīng)測試OK,使用時直接傳入對應(yīng)參數(shù)即可,直接上代碼

import smtplibfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartclass SendEMail(object): '''封裝發(fā)送郵件類''' def __init__(self, host, port, msg_from, pwd): self.msg_from = msg_from self.password = pwd # 郵箱服務(wù)器地址和端口 self.smtp_s = smtplib.SMTP_SSL(host=host, port=port) # 發(fā)送方郵箱賬號和授權(quán)碼 self.smtp_s.login(user=msg_from, password=pwd) def send_text(self, to_user, content, subject, content_type=’plain’): ''' 發(fā)送文本郵件 :param to_user: 對方郵箱 :param content: 郵件正文 :param subject: 郵件主題 :param content_type: 內(nèi)容格式:’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’): ''' 發(fā)送帶文件的郵件 :param to_user: 對方郵箱 :param content: 郵件正文 :param subject: 郵件主題 :param reports_path: 文件路徑 :param filename: 郵件中顯示的文件名稱 :param content_type: 內(nèi)容格式 ''' 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’): ’’’ 發(fā)送帶圖片的郵件 :param to_user: 對方郵箱 :param subject: 郵件主題 :param content: 郵件正文 :param filename: 圖片路徑 :param content_type: 內(nèi)容格式 ’’’ subject = subject msg = MIMEMultipart(’related’) # Html正文必須包含<img src='cid:imageid' alt='imageid' 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: img_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())

以上就是python 發(fā)送郵件的四種方法匯總的詳細(xì)內(nèi)容,更多關(guān)于python 發(fā)送郵件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 龙山县| 喀喇沁旗| 潍坊市| 综艺| 霸州市| 顺昌县| 体育| 桂林市| 白城市| 松阳县| 霍邱县| 上犹县| 冷水江市| 溆浦县| 赣州市| 深泽县| 西盟| 织金县| 闵行区| 金门县| 彭泽县| 柞水县| 儋州市| 韩城市| 文水县| 吴川市| 唐山市| 广西| 呼和浩特市| 枞阳县| 柳州市| 宝鸡市| 邛崃市| 丽江市| 婺源县| 甘肃省| 日喀则市| 克东县| 白山市| 宣汉县| 盘锦市|