Python

Python_发送邮件的模块

2018-09-07  本文已影响1人  blade_he

支持有附件的Email发送模块

"""
@version: 0.1
@author: Blade He
@license: Morningstar 
@contact: blade.he@morningstar.com
@site: 
@software: PyCharm
@file: emailutil.py
@time: 2018/9/7 15:59
"""
import os
import traceback
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
from email.mime.multipart import MIMEMultipart


def send_email(smtp_server,
               username,
               password,
               from_addr,
               to_addr,
               cc_addr,
               subject,
               content,
               content_type,
               attachfile,
               port=587):
    # 邮件发送和接收人配置
    msg = MIMEMultipart()
    msg['From'] = from_addr # 显示的发件人
    msg['To'] = to_addr
    if len(cc_addr.strip()) > 0:
        msg['Cc'] = cc_addr
    msg['Subject'] = Header(subject, 'utf-8')  # 显示的邮件标题

    # 需要传入的路径
    r = os.path.exists(attachfile)
    if r is False:
        msg.attach(MIMEText('no file...', content_type, 'utf-8'))
    else:
        # 邮件正文是MIMEText:
        msg.attach(MIMEText(content.strip(), content_type, 'utf-8'))
        filepart = MIMEApplication(open(attachfile, 'rb').read())
        filepart.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachfile))
        msg.attach(filepart)
    try:
        server = smtplib.SMTP(smtp_server, port)
        # server.set_debuglevel(1)  # 用于显示邮件发送的执行步骤
        # server.ehlo()
        # 如果是一般的smtp发送邮件,可以把下面一句注释
        server.starttls()
        # server.ehlo()
        server.login(username, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
    except Exception as e:
        print("Error: unable to send email")
        traceback.print_exc()
上一篇下一篇

猜你喜欢

热点阅读