工作中難免會出現自動發送電子郵件的需求,比如說做完自動化測試之后通過電子郵件的形式將結果反饋出來。Python中提供了標准庫smtplib來解決這一問題,該模塊定義了一個smtp客戶端會話對象,能夠將郵件發送給smtp服務端。具體用法請查看下面例子。
import smtplib from email.mime.text import MIMEText def send_email(from_user_name, from_address, password, to_address_list, subject, content, smtp_host): """ :param from_user_name: str> 發送郵箱的用戶名 :param from_address: str> 發送郵箱地址 :param password: str> 發送郵箱密碼 :param to_address_list: list> 接收郵箱地址 :param subject: str> 郵件主題 :param content: str> 郵件內容 :param smtp_host: str> smtp服務器地址 :return send_result: bool > 郵件是否發送成功 """ smtp = smtplib.SMTP(smtp_host, 465) smtp.starttls() smtp.set_debuglevel(1) smtp.ehlo(smtp_host) smtp.login(from_address, password) msg = MIMEText(content, _subtype='html', _charset='utf-8') msg['From'] = u'%s<%s>' % (from_user_name, from_address) msg['To'] = ",".join(to_address_list) msg['Subject'] = subject send_result = False try: smtp.sendmail(from_address, to_address_list, msg.as_string()) send_result = True except smtplib.SMTPException as e: print(str(e)) send_result = False finally: smtp.quit() return send_result if __name__ == '__main__': send_email( from_user_name='from_user_name', from_address='from_address@xxx.com', password='email_password', to_address_list=['a@xxx.com', 'b@xxx.com'], subject='test_subject', content='test_content', smtp_host='smtp.xxx.com' )
該例子中定義了send_email()函數實現了連接smtp服務端、登錄郵箱、發送郵件等功能。其中smtplib.SMTP(smtp_host, 465)在初始化實力時就已經進行了smtp連接,需要傳入服務端的host和port,所以入參465並不是固定的,要根據服務端的端口號來改變。
登錄SMTP服務器時往往會進行身份驗證,這里用到了smtp.login(from_address, password),入參是用於驗證的用戶名和密碼。
登錄完成后,可以通過smtp.sendmail(from_address, to_address_list, msg.as_string())把郵件發送給服務端,入參是發件人地址、收件人地址及郵件內容。
參考資料
- https://docs.python.org/zh-cn/3.9/library/smtplib.html