1. 程式人生 > 程式設計 >基於python SMTP實現自動傳送郵件教程解析

基於python SMTP實現自動傳送郵件教程解析

最近工作中的一個專案需要自動傳送一些資訊郵件到指定郵箱的需求,那麼如何實現Python自動傳送郵件的功能呢?接下來我們就來簡單的介紹下如何利用Python來實現自動傳送郵件的功能。

Python SMTP傳送郵件

SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議 ,說白了就是傳送郵件的協議,python的smplib庫對SMTP協議進行了簡單的封裝,提供了對SMTP的支援,可以傳送純文字郵件、HTML檔案以及帶附件的郵件。

首先我們構建一個SendEmailManager類,也是遵循著面向物件程式設計的思想來做,大體結構如下:

class SendEmailManager(object):

  def __init__(self,**kwargs):
    # 初始化引數
    ...

  def _get_conf(self,key):
    # 獲取配置引數
    ...

  def _init_conf(self):
    # 初始化配置引數
    ...

  def _login_email(self):
    # 登入郵箱伺服器
    ...
  def _make_mail_msg(self):
    # 構建文字郵件物件
    ...

  def do_send_mail(self):
    # 郵件傳送
    ...

def __init__(self,**kwargs)

類的初始化函式,可以用來設定物件屬性,並給予初始值,可以是引數或者固定值 ,其中引數**kwargs是將一個可變的關鍵字引數的字典傳給函式實參,這裡裡我們主要是對SMTP伺服器(這裡使用qq郵箱)、傳送郵件的代理郵箱、在郵箱中設定的客戶端授權密碼、可變引數進行一些初始化。具體程式碼如下:

# SMTP伺服器,這裡使用qq郵箱,其他郵箱自行百度
EMAIL_HOST = 'smtp.qq.com'
# 傳送郵件的代理郵箱
EMAIL_HOST_USER = '[email protected]'
# 在郵箱中設定的客戶端授權密碼,注意這裡不是郵箱密碼,如何獲取郵箱授權碼,請看本文最後教程
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxx'
def __init__(self,**kwargs):
  # 初始化引數
  self.email_host = EMAIL_HOST
  self.email_host_user = EMAIL_HOST_USER
  self.email_host_pass = EMAIL_HOST_PASSWORD
  self.kwargs = kwargs

def _get_conf(self,key)

主要負責通過key讀取 可變引數self.kwargs 字典裡的值,供其他函式使用。

def _get_conf(self,key):
  # 獲取配置引數
  value = self.kwargs.get(key)
  if key != "attach_file_list" and (value is None or value == ''):
    raise Exception("configuration parameter '%s' cannot be empty" % key)
  return value

def _init_conf(self)

該函式主要負責初始化 函式_get_conf 返回的配置引數, 以便接下來的函式可以呼叫相關配置引數。

def _init_conf(self):
  # 初始化配置引數
  print(self._get_conf('receives'))
  self.receives = self._get_conf('receives')
  self.msg_subject = self._get_conf('msg_subject')
  self.msg_content = self._get_conf('msg_content')
  self.msg_from = self._get_conf('msg_from')
  # attachment
  self.attach_file_list = self._get_conf('attach_file_list')

def _login_email(self)

登入郵件伺服器, 我這裡登陸的是qq郵箱的伺服器,埠號為465,其他郵箱埠號請自行百度,程式碼如下:

def _login_email(self):
  # 登入郵箱伺服器
  try:
    server = smtplib.SMTP_SSL(self.email_host,port=465)
    # set_debuglevel(1)可以打印出和SMTP伺服器互動的所有資訊
    server.set_debuglevel(1)
    # 登入郵箱
    server.login(self.email_host_user,self.email_host_pass)
    return server
  except Exception as e:
    print("mail login exception:",e)
    raise e

def _make_mail_msg(self)

該函式的功能為構建一個郵件例項物件,來處理郵件的內容。一封正常的郵件一般有收發件者資訊,郵件主題,郵件正文,有些郵件還附帶有附件,具體的設定參見如下程式碼:

def _make_mail_msg(self):
  # 構建郵件物件
  msg = MIMEMultipart()
  msg.attach(MIMEText(self.msg_content,'plain','utf-8'))
  # 郵件主題
  msg['Subject'] = Header(self.msg_subject,"utf-8")
  # 發件人郵箱資訊
  msg['From'] = "<%s>" % self.msg_from
  # msg['From'] = Header(self.msg_from + "<%s>" % self.email_host_user,"utf-8")
  msg['To'] = ",".join(self.receives)
  print("---",self.attach_file_list)
  if self.attach_file_list:
    for i,att in enumerate(self.attach_file_list):
      # 構造附件,傳送當前目錄下的檔案
      if not att:
        break
      att_i = MIMEText(open(att,'rb').read(),'base64','utf-8')
      att_i["Content-Type"] = 'application/octet-stream'
      # 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
      att_i["Content-Disposition"] = 'attachment; filename="%s"' % att
      msg.attach(att_i)
  return msg

def do_send_mail(self)

傳送郵件,就是把上幾個函式串起來,直接上程式碼:

def do_send_mail(self):
  # 郵件傳送
  try:
    self._init_conf()
    server = self._login_email()
    msg = self._make_mail_msg()
    server.sendmail(self.email_host_user,self.receives,msg.as_string())
    server.close()
    print("傳送成功!")
  except Exception as e:
    print("郵件傳送異常",e)

配置引數,測試能否正常傳送郵件:

if __name__ == "__main__":
  mail_conf = {
    'msg_from': '[email protected]',# 郵件傳送者的地址
    'receives': ['[email protected]','[email protected]',],# 郵件接收者的地址,這是個list,因為郵件的接收者可能不止一個
    'msg_subject': 'Python 自動傳送郵件測試!!',# 郵件的主題
    'msg_content': '人生苦短,我用python!!!',# 郵件的內容
    'attach_file_list': {"test_file1.py": "test.py","test_file2.pem": "./public.pem"},# 為附件檔案路徑列表,也是個list,也可沒有這項
  }

  manager = SendEmailManager(**mail_conf)
  manager.do_send_mail()


基於python SMTP實現自動傳送郵件教程解析

ok,傳送成功,新增附件也是沒問題的。

開始我們講的獲取客戶端郵箱的授權碼,教程如下(以qq郵箱為例):

基於python SMTP實現自動傳送郵件教程解析

好了,目標完成。

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