1. 程式人生 > 程式設計 >Python基於smtplib模組傳送郵件程式碼例項

Python基於smtplib模組傳送郵件程式碼例項

smtplib模組負責傳送郵件:是一個傳送郵件的動作,連線郵箱伺服器,登入郵箱,傳送郵件(有發件人,收信人,郵件內容)。

email模組負責構造郵件:指的是郵箱頁面顯示的一些構造,如發件人,收件人,主題,正文,附件等。

email模組下有mime包,mime英文全稱為“Multipurpose Internet Mail Extensions”,即多用途網際網路郵件擴充套件,是目前網際網路電子郵件普遍遵循的郵件技術規範。

該mime包下常用的有三個模組:text,image,multpart。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

#郵件伺服器資訊
smtp_server = "smtp.qq.com"
port = 465 # For starttls
sender_email = "[email protected]"
password="" #get password from mailsetting

#傳送郵件資訊,可以傳送給多個收件人
receivers=["[email protected]","[email protected]"]
subject="This is import Python SMTP 郵件(檔案傳輸) 多媒體測試"

# message = MIMEText(text,"plain","utf-8") #文字郵件
message = MIMEMultipart()
message["Subject"] = Header(subject,"utf-8")
message["from"] = sender_email
message["to"] = ",".join(receivers)
# 郵件正文內容
text="""
Dear Sir:
how are you ? \n
for detail information pls refer to attach1。\n
The files you need are as followed.\n
If you have any concern pls let me known.\n
enjoy your weekend.\n
BEST REGARDS \n
"""
# message.attach(MIMEText('for detail information pls refer to attach1。\n The files you need are as followed. \n If you have any concern pls let me known. \n enjoy your weekend','plain','utf-8')
message.attach(MIMEText(text,'utf-8'))

# 構造附件1
attach_file1='IMG1965.JPG'

attach1 = MIMEText(open(attach_file1,'rb').read(),'base64','utf-8')
attach1["Content-Type"] = 'application/octet-stream'
attach1["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file1)
message.attach(attach1)

# 構造附件2
attach_file2='YLJ.jpg'
attach2 = MIMEText(open(attach_file2,'utf-8')
attach2["Content-Type"] = 'application/octet-stream'
attach2["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file2)
message.attach(attach2)

# Try to log in to server and send email
# server = smtplib.SMTP_SSL(smtp_server,port)
server = smtplib.SMTP_SSL(smtp_server,port)

try:
  server.login(sender_email,password)
  server.sendmail(sender_email,receivers,message.as_string())
  print("郵件傳送成功!!!")
  print("Mail with {0} & {1} has been send to {2} successfully.".format(attach_file1,attach_file2,receivers))
except Exception as e:
  # Print any error messages to stdout
  print("Error: 無法傳送郵件")
  print(e)
finally:
  server.quit()

結果

郵件傳送成功!!!

Mail with IMG1965.JPG & IMG1963.jpg has been send to ['[email protected]','[email protected]'] successfully.

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。