介紹:
發郵件需要用到python兩個模組,smtplib和email,這倆模組是python自帶的,只需import即可使用。smtplib模組主要負責傳送郵件,email模組主要負責構造郵件。其中mimetext()定義郵件正文,header()定義郵件標題。mimemulipart模組構造帶附件。
大致流程:
1、發件人需要登入郵箱、涉及發件人的登入賬號和密碼----smtplib
2、構造郵件內容:1)確定郵件內容,涉及附件的話,需要設定有郵件體物件----mimemulipart
msg_root = mimemultipart('mixed')
2)郵件內容:發件人、收件人、主題、正文、附件
其中:收件人包括單人收件 和 多人收件
主題需要匯入:from email.header import header
3、使用smtplib傳送郵件
4、各模組語法介紹:
導圖總結如下:
本人**樣例:
#-*- coding:utf-8 -*-
import smtplib
from email.header import header
from email.mime.multipart import mimemultipart
from email.mime.text import mimetext
from email.mime.image import mimeimage
from utils.logger import logger
logger = logger(logger='sendemail').get_log()
class sendemail():
def send_email(self,to,filename):
#設定賬戶和密碼
sender_email = '[email protected]'
sender_pass = '####'
logger.info('設定發件郵箱登入賬號和密碼')
#設定總的郵件體物件,物件型別為mixed
msg_root = mimemultipart('mixed')
logger.info('設定總的郵件體物件,物件型別為mixed')
#郵件新增的頭尾資訊等
msg_root['from'] = 'amy@mailcom'
logger.info('設定發件人的郵箱資訊')
msg_root['to'] = to
logger.info('設定收件人的郵箱資訊')
#郵件主題,顯示在接收郵件的預覽頁面
subject = 'python sendmail test successful'
msg_root['subject'] = header(subject,'utf-8')
#構造文字內容
text_sub = mimetext(text_info,'plain','utf-8')
msg_root.attach(text_sub)
#構造附件
html_file = open(filename,'rb').read()
html = mimetext(html_file,'base64','utf-8')
#郵件內容
html['content-disposition'] = 'attachment;filename="jetty_report.html"'
msg_root.attach(html)
#傳送郵件
try:
sftp_obj = smtplib.smtp('lsmtp.com',25)
sftp_obj.login(sender_email,sender_pass)
sftp_obj.sendmail(sender_email,to,msg_root.as_string())
sftp_obj.quit()
print('sendemail successful')
except exception as e:
print('sendemail failed next is the reason')
print(e)
if __name__ == '__main__':
# to = '[email protected]'
to = ['[email protected]','[email protected]','[email protected]']
to = ';'.join(to)
logger.info('收件人為多個')
file_name = r'd:\api\test_report\jetty_report.html'
send = sendemail()
send.send_email(to,file_name)
參考: html傳送郵件 Python傳送郵件(三十)
簡單郵件傳輸協議 smtp 是一種協議,用於在郵件伺服器之間傳送電子郵件和路由電子郵件。python提供smtplib模組,該模組定義了乙個smtp客戶端會話物件,可用於使用smtp或esmtp偵聽器守護程式向任何網際網路機器傳送郵件。這是乙個簡單的語法,用來建立乙個smtp物件,稍後將演示如何用它...
python 傳送郵件
coding utf 8 import smtplib from email.mime.text import mimetext from email.header import header 檔案形式的郵件 def email file mail host smtp.qq.com 郵箱伺服器 ma...
python 傳送郵件
smtp mail transfer protocol 即簡單郵件傳輸協議,它是一組用於由源位址到目的位址傳送郵件的規則,由它來控制信件的中轉方式。python的smtplib提供了一種很方便的途徑傳送電子郵件。它對smtp協議進行了簡單的封裝。直接貼 coding utf 8 import smt...