用Python編寫的發郵件代碼

      發郵件用到的Python庫是smtplib和email。簡單來說,smtplib庫主要是用於負責和郵件服務器進行通訊,email庫則主要用於規定編寫郵件的頭、主體、內容、附件等。

      發郵件之前我們需要用Python登錄smtp服務器,這樣纔能有發送權限,所以,我們需要去郵箱手動開啓smtp服務,然後記住服務器授權碼(授權碼意思是,你可以不用我的網頁郵箱或者郵箱app登錄,你可以用郵箱賬號+授權碼在後臺來獲取郵箱服務器的內容)

本次發送一個簡單的郵件,本次發送一個簡單的文字郵件,然後添加一張圖片作爲附件:

代碼如下:

import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#sender是郵件發送人郵箱,passWord是服務器授權碼,mail_host是服務器地址(這裏是QQsmtp服務器)
sender = '[email protected]'#
passWord = 'xxx'
mail_host = 'smtp.qq.com'
#receivers是郵件接收人,用列表保存,可以添加多個
receivers = ['[email protected]','[email protected]']

#設置email信息
msg = MIMEMultipart()
#郵件主題
msg['Subject'] = input(u'請輸入郵件主題:')
#發送方信息
msg['From'] = sender
#郵件正文是MIMEText:
msg_content = input(u'請輸入郵件主內容:')
msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
# 添加附件就是加上一個MIMEBase,從本地讀取一個圖片:
with open(u'/Users/xxx/1.jpg', 'rb') as f:
    # 設置附件的MIME和文件名,這裏是jpg類型,可以換png或其他類型:
    mime = MIMEBase('image', 'jpg', filename='Lyon.png')
    # 加上必要的頭信息:
    mime.add_header('Content-Disposition', 'attachment', filename='Lyon.png')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # 把附件的內容讀進來:
    mime.set_payload(f.read())
    # 用Base64編碼:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    msg.attach(mime)

#登錄併發送郵件
try:
    #QQsmtp服務器的端口號爲465或587
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.set_debuglevel(1)
    s.login(sender,passWord)
    #給receivers列表中的聯繫人逐個發送郵件
    for item in receivers:
        msg['To'] = to = item
        s.sendmail(sender,to,msg.as_string())
        print('Success!')
    s.quit()
    print ("All emails have been sent over!")
except smtplib.SMTPException as e:
    print ("Falied,%s",e)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章