Python | SMTP,明文、TLS、SSL一次完成

近期有利用到 Python 透過 smtplib 發送電子郵件,因此寫了個簡單的 class 方便使用。
import smtplib
from os.path import basename
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formatdate
import html


class SendMail:
    def __init__(self, send, receiver, subject, body, files):
        self.mail = MIMEMultipart()
        self.mail['Date'] = formatdate(localtime=True) # 設定發信時間
        self.mail['Subject'] = subject # 設定信件標題
        self.mail.attach(MIMEText(html.unescape(body), 'html', 'utf-8')) # HTML解碼

        for f in files or []: # 載入附件
            with open(f, "rb") as fil:
                part = MIMEApplication(
                    fil.read(),
                    Name=basename(f)
                )
            # After the file is closed
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
            self.mail.attach(part)

        self._send = send # 設定寄信者
        self._receiver = receiver # 設定收信者

    # 此為設定寄信芳和收信方的名稱,不設定將會依照顯示信箱地址
    def set_header(self, send_header=None, receiver_header=None):
        if send_header is not None:
            self.mail['From'] = Header(send_header, 'utf-8')
        if receiver_header is not None:
            self.mail['To'] = Header(receiver_header, 'utf-8')

    # 以TLS方式連接SMTP
    def send_tls_mail(self, account, password, server, port=587):
        smtp = smtplib.SMTP(server, port)
        smtp.ehlo()
        smtp.starttls()
        smtp.login(account, password)
        smtp.sendmail(self._send, self._receiver, self.mail.as_string())
        smtp.close()

    # 以明文方式連接SMTP,含登入訊息
    def send_mail_w_login(self, account, password, server, port=25):
        smtp = smtplib.SMTP(server, port)
        smtp.ehlo()
        smtp.login(account, password)
        smtp.sendmail(self._send, self._receiver, self.mail.as_string())
        smtp.close()

    # 以明文方式連接SMTP
    def send_mail(self,server, port=25):
        smtp = smtplib.SMTP(server, port)
        smtp.ehlo()
        smtp.sendmail(self._send, self._receiver, self.mail.as_string())
        smtp.close()

    # 以SSL方式連接SMTP
    def send_ssl_mail(self, account, password, server, port=465):
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.ehlo()
        smtp.login(account, password)
        smtp.sendmail(self._send, self._receiver, self.mail.as_string())
        smtp.close()
Github

留言

這個網誌中的熱門文章

Leetcode:Number of 1 Bits