Python_메일 발송 모듈

1885 단어

첨부 파일 지원 Email 발송 모듈

"""
@version: 0.1
@author: Blade He
@license: Morningstar 
@contact: [email protected]
@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()

좋은 웹페이지 즐겨찾기