1. 程式人生 > 其它 >python傳送郵件的簡單使用

python傳送郵件的簡單使用

主程式碼如下:

點選檢視程式碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/26 9:46 上午
# @Author  : Ayden
# @Site    : 
# @File    : send_email.py
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
import pathlib
from conf.setting import *
from common.log import Log

log = Log().log()

def send_mail(host="xxxxxx", port=None, title=None, send_files=None, content=None):
    if not content:
        title = "車聯網介面自動化測試報告"
    if not content:
        content = "     \n\n附件為車聯網雲平臺介面自動化測試報告,請使用瀏覽器進行檢視,訪問地址為:\n" \
                  "     http://{}:{}\n" \
                  "\n\n本郵件為自動發出,請勿回覆".format(host, port)
    mail_host = send_email["mail_host"]
    mail_port = send_email["mail_port"]
    mail_user = send_email["mail_user"]
    mail_password = send_email["mail_pass"]
    # log.debug("發件資訊為:{}".format(send_email))
    try:
        msg = MIMEMultipart()
        msg['Subject'] = title
        msg['To'] = ",".join(receive_email)
        print(msg['To'])
        msg['From'] = mail_user
        body = MIMEText(content, 'plain', 'utf-8')
        if send_files:
            #for send_file in send_files:
            part_attach = MIMEApplication(open(send_files, 'rb').read())  # 開啟附件
            # 為附件命名
            part_attach.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(send_files).name)
            # 新增附件
            msg.attach(part_attach)
        msg.attach(body)
        smtp = smtplib.SMTP(mail_host, mail_port)
        smtp.starttls()
        smtp.login(mail_user, mail_password)
        smtp.sendmail(mail_user, receive_email, msg.as_string())
        # log.debug("郵件傳送成功")
        smtp.quit()
    except Exception as e:
        log.debug("郵件傳送失敗,原因是{}".format(e))

其中setting配置如下:

點選檢視程式碼
# 發件人電子郵箱
send_email = {"mail_host": "smtp.163.com", "mail_port": 25, "mail_user": "[email protected]",
             "mail_pass": "XSJLZTQHSMAKPCMX"}
# 收件人電子郵箱
receive_email = ['[email protected]', '[email protected]']

備註:以上日誌模組請自行去除

Email:[email protected]