2021/9/15更新:添加圖檔附件+添加抄送
注意:msg[‘Cc’] = ‘,’.join(cc) 這裡表示在郵件的抄送欄寫明抄送給誰,但是不代表會被發送。是以必須把cc加入到receiver中一起發送才可以。
# sender: 發件郵箱, string
# receiver: 收件郵箱, string
# cc: 抄送, list
# subject: 主題
# content: 正文内容(html)
# imgs: 圖檔附件 list
# attaches: 其他附件 list
# my_pass: 發信密碼
def send_mail(sender, receiver, cc, subject, content, imgs, attaches, my_pass):
# ret是傳回值, False表示發送失敗
ret = True
try:
# 發送html和附件
msg = MIMEMultipart('related')
msg['From'] = formataddr(["", sender])
msg['To'] = formataddr(["", receiver])
msg['Subject'] = subject
msg['Cc'] = ','.join(cc)
# 填寫正文内容
msgTxt = MIMEText(content, "html", "utf-8")
msg.attach(msgTxt)
# 添加img
for img in imgs:
att = addimg(img, '<image1>')
att["Content-Type"] = 'application/octet-stream'
# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att["Content-Disposition"] = 'attachment; filename=%s' % img
msg.attach(att)
# 添加其他附件
for f in attaches:
att = MIMEApplication(open(f, 'rb').read())
att["Content-Type"] = 'application/octet-stream'
# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att["Content-Disposition"] = 'attachment; filename=%s' % f
msg.attach(att)
# 登入郵件伺服器
server = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)
server.login(sender, my_pass)
server.sendmail(sender, [receiver,]+cc, msg.as_string())
server.quit()
except Exception as e:
print("send_mail:failed!")
print(e)
ret = False
return ret
2020/12/14更新:騰訊企業郵不需要取得發信密碼
今天PM要求用公共郵箱發信,是以。。我發現不并不需要開啟安全登入+擷取發信密碼。
代碼不用改,my_pass直接用登入密碼即可。
示例代碼
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
def send_mail(sender, receiver, subject, attaches, my_pass):
ret = True
try:
msg = MIMEMultipart()
# 郵件顯示的發信人名稱
msg['From'] = formataddr(["大資料XXX", sender])
msg['To'] = formataddr(["生産", receiver])
# 郵件顯示的主題
msg['Subject'] = subject
server = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465) # 騰訊企業郵
# 這個是普通qq郵箱的伺服器
#server = smtplib.SMTP_SSL("smtp.qq.com", 465)
for f in attaches:
att = MIMEApplication(open(f, 'rb').read())
att["Content-Type"] = 'application/octet-stream'
# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att["Content-Disposition"] = 'attachment; filename=%s' % f
msg.attach(att)
server.login(sender, my_pass)
server.sendmail(sender, [receiver, ], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
sender = '[email protected]'
receiver = '[email protected]'
my_pass = '**********'
attaches = [準備發送的檔案名清單]
send_mail(sender, receiver, "訂單更新結果", attaches, my_pass)
要點在于如何擷取這個my_pass,就是使用郵箱發信的密碼。這個密碼并不是發件人登入郵箱伺服器所用的密碼(其實不太确切)。
對于普通qq郵箱
設定 - 賬戶 -
用這個授權碼當my_pass。
騰訊企業郵
我是公司業務嘛,肯定不能用個人郵箱對吧。首先開啟安全登入,之後可能會被退出賬戶吧,掃碼進來之後,擷取用戶端專用密碼即可。用戶端專用密碼就是my_pass。