您的位置:首頁技術文章
文章詳情頁

利用Python發送郵件或發帶附件的郵件

瀏覽:2日期:2022-07-05 16:58:11

本文使用的是163郵件進行測試。

注:163郵箱現在需要使用 客戶端授權碼 進行測試,不再支持郵箱密碼進行測試。

1、使用Python發Text 郵件

import smtplib# 發送字符串的郵件from email.mime.text import MIMEText# 設置服務器所需信息fromEmailAddr = ’發件人郵箱地址’ # 郵件發送方郵箱地址password = ’email password’ # 密碼(部分郵箱為授權碼)toEmailAddrs = [’接收方地址’] # 郵件接受方郵箱地址,注意需要[]包裹,這意味著你可以寫多個郵件地址群發# 設置email信息# ---------------------------發送字符串的郵件-----------------------------# 郵件內容設置message = MIMEText(’hello,test Python send Email.’, ’plain’, ’utf-8’)# 郵件主題message[’Subject’] = ’python test email’# 發送方信息message[’From’] = fromEmailAddr# 接受方信息message[’To’] = toEmailAddrs[0]# ---------------------------------------------------------------------# 登錄并發送郵件try: server = smtplib.SMTP(’smtp.163.com’) # 163郵箱服務器地址,端口默認為25 server.login(fromEmailAddr, password) server.sendmail(fromEmailAddr, toEmailAddrs, message.as_string()) print(’success’) server.quit()except smtplib.SMTPException as e: print('error:', e)

2、使用Python發送帶附件的郵件

import smtplib# 發送字符串的郵件from email.mime.text import MIMEText# 需要 MIMEMultipart 類from email.mime.multipart import MIMEMultipart# 設置服務器所需信息fromEmailAddr = ’發件人郵箱地址’ # 郵件發送方郵箱地址password = ’email password’ # 密碼(部分郵箱為授權碼)toEmailAddrs = [’收件人地址’] # 郵件接受方郵箱地址,注意需要[]包裹,這意味著你可以寫多個郵件地址群發# 設置email信息# ---------------------------發送帶附件郵件-----------------------------# 郵件內容設置message = MIMEMultipart()# 郵件主題message[’Subject’] = ’python test email’# 發送方信息message[’From’] = fromEmailAddr# 接受方信息message[’To’] = toEmailAddrs[0]# 郵件正文內容message.attach(MIMEText(’hello,test Python send Email’, ’plain’, ’utf-8’))# 構造附件att1 = MIMEText(open(’text.txt’, ’rb’).read(), ’base64’, ’utf-8’)att1[’Content-type’] = ’application/octet-stream’att1[’Content-Disposition’] = ’attachment; filename='test.zip'’message.attach(att1)# ---------------------------------------------------------------------# 登錄并發送郵件try: server = smtplib.SMTP(’smtp.163.com’) # 163郵箱服務器地址,端口默認為25 server.login(fromEmailAddr, password) server.sendmail(fromEmailAddr, toEmailAddrs, message.as_string()) print(’success’) server.quit()except smtplib.SMTPException as e: print('error:', e)

以上就是利用Python發送郵件或發帶附件的郵件的詳細內容,更多關于python 發送郵件的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区