1. 程式人生 > >python 發送郵件 email

python 發送郵件 email

{} 目標 string erro con exce posit def ima

import os
import smtplib
import logging
from report_system.utils import excel_util
from report_system.utils import style_util
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import
MIMEMultipart # 第三方 SMTP 服務 mail_host = "smtp.mxhichina.com" # 設置服務器 mail_user = "[email protected]***.com" # 用戶名 mail_pass = "mima" # 口令 sender = [email protected]***.com def send_files_mail(files, text, title, html=None, receiver=‘name@***.com, content_type=plain, tab=5):
try: """ 發送附件信息 :param files: 要發送的發送文件的集合信息 :param title: 要發送的標題 :param text: 發送的文件的內容 :param receiver: 想要發送的目標人物 eg: ‘[email protected]***.com;[email protected]***.com‘ :param content_type: content_type 默認 plain :return:
""" # 創建一個帶附件的實例 message = MIMEMultipart() message[From] = sender message[To] = receiver message[Subject] = Header(title, utf-8) # 郵件正文內容 message.attach(MIMEText(text, content_type, utf-8)) if html: message.attach(MIMEText(html, html, utf-8)) contype = application/octet-stream maintype, subtype = contype.split(/, 1) for file in files if isinstance(files, list) else str(files).split(;): # 構造附件 data = open(file.strip(), rb) file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() encoders.encode_base64(file_msg) basename = os.path.basename(file) file_msg.add_header(Content-Disposition, attachment, filename=basename) message.attach(file_msg) smtp_obj = smtplib.SMTP_SSL(host=mail_host) # 註意:如果遇到發送失敗的情況(提示遠程主機拒接連接),這裏要使用SMTP_SSL方法 smtp_obj.connect(mail_host) smtp_obj.login(mail_user, mail_pass) smtp_obj.sendmail(sender, str(receiver).strip().split(";"), message.as_string()) logging.info("郵件發送成功!!!to = {}".format(receiver)) logging.info("發送成功的文件是 files = {}".format(files)) smtp_obj.quit() except Exception as e: if tab > 0: logging.error(發送失敗! 正在嘗試重新發送!請稍等。。。。。。) send_files_mail(files, text, title, receiver=receiver, content_type=content_type, tab=tab - 1) else: logging.exception(e)

python 發送郵件 email