Python——利用Python發送郵件(此處示例QQ郵箱)

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 16:02:17 2019

@author: liuxiaohuan
"""

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

sender = '[email protected]'
receiver = list()#接收者列表
receiver.append('[email protected]')
copyReceive = list()#抄送者列表
copyReceive.append(sender)#將發件人添加到抄送列表
username = '[email protected]'#發件人郵箱賬號
password = 'uakdghjbupowasdf'#授權密碼
mailall=MIMEMultipart()
mailall['Subject'] = "凱凱是頭豬" #記住一定要設置,並且要稍微正式點
mailall['From'] = sender #發件人郵箱
mailall['To'] = ';'.join(receiver) #收件人郵箱,不同收件人郵箱之間用;分割
mailall['CC'] = ';'.join(copyReceive)  #抄送郵箱
mailcontent = '凱凱是頭豬'
mailall.attach(MIMEText(mailcontent, 'plain', 'utf-8'))
mailAttach = '測試郵件附件內容'
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
filename = r'C:/Users/liuxiaohuan/Desktop/1.txt'#附件文件所在路徑
attfile = MIMEBase(maintype, subtype)
attfile.set_payload(open(filename, 'rb').read())
attfile.add_header('Content-Disposition', 'attachment',filename=('utf-8', '', filename))#必須加上第三個參數,用於格式化輸出
encoders.encode_base64(attfile)
mailall.attach(attfile)
fullmailtext = mailall.as_string()
smtp = smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver+copyReceive, fullmailtext)#發送的時候需要將收件人和抄送者全部添加到函數第二個參數裏
smtp.quit()

溫馨提示:當附件內容包含有中文時,會發送失敗,此處報錯:UnicodeEncodeError: 'ascii' codec can't encode characters in position 800-814: ordinal not in range(128)

解決辦法:添加如下代碼:

from email import encoders
encoders.encode_base64(attfile)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章