成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

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

python使用smtplib模塊發(fā)送郵件

瀏覽:6日期:2022-07-02 08:19:39

使用smtplib模塊發(fā)送郵件,供大家參考,具體內(nèi)容如下

1)使用smtplib模塊發(fā)送簡單郵件

步驟:

1.連接SMTP服務(wù)器,并使用用戶名、密碼登陸服務(wù)器2.創(chuàng)建EmailMessage對象,該對象代表了郵件本身3.調(diào)用sendmail()方法發(fā)送郵件

示例:

我用自己的QQ郵箱(英文地址)給自己(原始地址)發(fā)一封郵件(QQ郵箱需要授權(quán)碼(詳見)) smtplib.SMTP() 代表的普通SMTP連接(默認(rèn)端口21) smtplib.SMTP_SSL() 代表基于SSL的SMTP連接(默認(rèn)端口456,安全)

import smtplibimport email.messagefromaddr = ’wk_helloworld@qq.com’ # 賬號password = ’****************’ # QQ授權(quán)碼conn = smtplib.SMTP_SSL(’smtp.qq.com’, 465) # 創(chuàng)建SMTP連接 conn.login(fromaddr, password) # 登錄郵件服務(wù)器msg = email.message.EmailMessage() # 創(chuàng)建郵件對象msg.set_content(’您好,Python郵件’) # 設(shè)置郵件內(nèi)容(普通郵件)conn.sendmail(fromaddr, [’929667257@qq.com’], msg.as_string()) # 發(fā)送郵件conn.quit() # 退出連接

python使用smtplib模塊發(fā)送郵件

2)發(fā)送內(nèi)容完整的郵件

為郵件設(shè)置標(biāo)題、發(fā)件人名字、收件人名(設(shè)置 EmailMessage 對象對應(yīng)的屬性) EmailMessage的set_content() 方法的第二個參數(shù)設(shè)置為 html 可將郵件內(nèi)容改為 HTML 格式

import smtplibimport email.messagefromaddr = ’wk_helloworld@qq.com’password = ’****************’ conn = smtplib.SMTP_SSL(’smtp.qq.com’, 465)conn.login(fromaddr, password) msg = email.message.EmailMessage()msg.set_content(’<h2>HTML郵件<h2>’ + ’<div style='border:1px:solid red'>HTML郵件內(nèi)容</div>’, ’html’, ’UTF-8’)msg[’subject’] = ’HTML郵件’msg[’from’] = ’癡迷<%s>’ % fromaddrmsg[’to’] = ’淡然<%s>’ % ’929667257@qq.com’conn.sendmail(fromaddr, [’929667257@qq.com’], msg.as_string())conn.quit()

python使用smtplib模塊發(fā)送郵件

3)發(fā)送圖文并茂的郵件

在郵件中插入圖片,需要先調(diào)用 EmailMessage 的 add_attachment() 方法來添加附件,該方法參數(shù):

maintype:指定附件的主要類型 subtype:指定附件的子類型 filename:指定該附件的文件名 cid=img:指定該附件的資源 ID

通過<img…/>元素來插入附件中的圖片(引用附件的cid屬性)

import smtplibimport email.messageimport email.utilsfromaddr = ’wk_helloworld@qq.com’password = ’****************’toaddr = ’929667257@qq.com’ conn = smtplib.SMTP_SSL(’smtp.qq.com’, 465)conn.login(fromaddr, password) msg = email.message.EmailMessage()first_id = email.utils.make_msgid()msg.set_content(’<h2>HTML郵件<h2>’ + ’<div style='border:1px:solid red'>html郵件內(nèi)容</div>’ + ’<img src='cid:’ + first_id[1:-1] + ’'>’, ’html’, ’UTF-8’)msg[’subject’] = ’HTML郵件’msg[’from’] = ’wk<%s>’ % fromaddrmsg[’to’] = ’k<%s>’ % toaddr# 添加附件with open(’圖1.jpg’, ’rb’) as f: # 附件指定cid后,郵件正文可通過該cid來引用該圖片 msg.add_attachment(f.read(), maintype=’image’, subtype=’jepg’, filename=’test1.jpg’, cid=first_id)with open(’圖2.jpg’, ’rb’) as f: msg.add_attachment(f.read(), maintype=’image’, subtype=’jepg’, filename=’test2.jpg’)# with open(’圖3.gif’, ’rb’) as f:# msg.add_attachement(f.read(), maintype=’image’, subtype=’gif’, filename=’test.jpg’)conn.sendmail(fromaddr, [toaddr], msg.as_string())conn.quit()

python使用smtplib模塊發(fā)送郵件

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章: