本文實例為大家分享了Python實現(xiàn)發(fā)送QQ郵件的封裝代碼,供大家參考,具體內(nèi)容如下
封裝code
import smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Header# type=plain 文本格式 默認(rèn)# type=html 網(wǎng)頁格式# type=image 帶本地圖片的html# type=file 帶附件# 帶圖片時,msg為html格式# 示例:'''msg ='<p>Python 郵件發(fā)送測試...</p><p>圖片演示:</p><p><img src="cid:image1"></p>''''class MyQQEmail: __mail_user = '' # 登陸郵箱 __mail_pass = '' # 郵箱授權(quán)碼 __senderName= '' # 發(fā)件人 def __init__(self,user,pas,name) -> None: self.__mail_user=user self.__mail_pass=pas self.__senderName=name def sendQQEmail(self,receiver, title, msg, type='plain', filePaths=[], fileNames=[], imagePaths=None): if receiver == '': return False mail_host = 'smtp.qq.com' mail_port = 465 # qq smtp端口465 sender = self.__mail_user type = type.lower() if type.__eq__('plain') or type.__eq__('html'): message = MIMEText(msg, type, 'utf-8') elif type.__eq__('file') or type.__eq__('image'): message = MIMEMultipart() else: return False try: message['From'] = Header(self.__senderName, 'utf-8') message['To'] = Header(str(receiver), 'utf-8') subject = title message['Subject'] = Header(subject, 'utf-8') if type.__eq__('file') or type.__eq__('image'): # 郵件正文內(nèi)容 if imagePaths is not None: message.attach(MIMEText(msg, 'html', 'utf-8')) # 添加圖片 if imagePaths is not None: for index,imagePath in enumerate(imagePaths,1): # 指定圖片為當(dāng)前目錄 fp = open(imagePath, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定義圖片 ID,在 HTML 文本中引用 msgImage.add_header('Content-ID', '<image'+str(index)+'>') message.attach(msgImage) else: message.attach(MIMEText(msg, 'plain', 'utf-8')) # 構(gòu)造附件,傳送filePath制定文件 for filePath, fileName in zip(filePaths, fileNames): att = MIMEText(open(filePath, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' # 郵件中顯示文件名 att["Content-Disposition"] = 'attachment; filename="' + fileName + '"' message.attach(att) except Exception as e: print(e) return False try: smtpObj = smtplib.SMTP_SSL(mail_host, mail_port) smtpObj.login(self.__mail_user, self.__mail_pass) smtpObj.sendmail(sender, receiver, message.as_string()) smtpObj.quit() return True except Exception as e: print(e) return False使用demo
發(fā)送純文本
qq=MyQQEmail('登陸郵箱','郵箱授權(quán)碼','發(fā)件人')qq.sendQQEmail(['收件人郵箱1','收件人郵箱2'], "標(biāo)題", '內(nèi)容')發(fā)送html
from smtp.myqqemail import MyQQEmailfrom urllib import requestresponse = request.urlopen("http://www.vove7.cn:800/getCopyright.php") # 打開網(wǎng)站htmlContent=response.read() #獲取網(wǎng)站內(nèi)容myqqemail=MyQQEmail('xxx@qq.com','xxxxxx','發(fā)件人')if myqqemail.sendQQEmail(['xxx@qq.com'],title="html測試",msg=htmlContent,type='html'): print('Send successful')else: print('Send failed')發(fā)送帶圖片內(nèi)容
注意圖片和<img src="cid:image1"><img src="cid:image2">中'image_index'保持一致
from smtp.myqqemail import MyQQEmailmsg = '<p>Python 郵件發(fā)送測試...</p><p>圖片演示:</p><p><img src="cid:image1"><img src="cid:image2"></p>'myQQEmail=MyQQEmail('xxx@qq.com','xxxxxx','發(fā)件人')if myQQEmail.sendQQEmail( ['xxx@qq.com'], '圖片and附件', msg, type='image', filePaths=['../two/t.py', 'B.txt'], fileNames=['test.txt', 'B.txt'], imagePaths=['image.jpg','image.jpg']): print('Send successful')else: print('Send failed')發(fā)送附件
fileName為顯示名
from smtp.myqqemail import MyQQEmailqqemail=MyQQEmail('xxx@qq.com','xxxxx','發(fā)件人')if qqemail.sendQQEmail( ['xxx@qq.com'], '附件',msg='附件測試', type='file',filePaths=['../two/t.py','B.txt'], fileNames=['test.txt','B.txt']): print('Send successful')else: print('Send failed')發(fā)送圖片內(nèi)容帶附件
from smtp.myqqemail import MyQQEmailmsg = '<p>Python 郵件發(fā)送測試...</p><p>圖片演示:</p><p><img src="cid:image1"><img src="cid:image2"></p>'qqemail=MyQQEmail('xxx@qq.com','xxx','發(fā)件人')if qqemail.sendQQEmail( ['xxx@qq.com'], '附件&圖片',msg, type='file',filePaths=['../two/t.py','B.txt'], fileNames=['test.txt','B.txt'], imagePaths=['image.jpg','image.jpg']): print('Send successful')else: print('Send failed')最后,修改代碼可簡化參數(shù)type
獲取QQ郵箱登陸授權(quán)碼
設(shè)置->賬戶->

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
|
新聞熱點
疑難解答
圖片精選