2019-10-05

【python 2.7】寄發郵件功能

 
#!/usr/bin/python
#-*- coding:utf-8 -*-

...
...

from smtplib import SMTP  
from smtplib import SMTPRecipientsRefused  
from poplib import POP3
from email.mime.text import MIMEText

...
...

# 定義 mail 相關的變數
smtpserver = '郵件主機 IP 或 網址'
username = '發送郵件的帳號'
password = '發送郵件的密碼'
sMaillist = 'johnber@email.hanshin.com.tw,johnbertw@gmail.com'    # 收件人列表, 以逗點分隔, 中間無空白


# 寄送郵件函式
def SendMail(sender, maillist, title, content):
    # 將收件人分隔開
    lstReceiver = maillist.split(",")

    lstMail = MIMEText(content, 'plain', 'utf-8')    # 寄發純文字格式的信件
    lstMail['From'] = sender
    lstMail['To'] = maillist
    lstMail['Subject'] = title
    # sendSer = SMTP("smtp.gmail.com:587")
    sendSer = SMTP(smtpserver)
    sendSer.ehlo()
    sendSer.starttls()    # 主機有使用 TLS 加密連線設定者適用
    sendSer.login(username, password)
    sendSer.sendmail(username, lstReceiver, lstMail.as_string())

...
...

def main():
    # 信件內容, 以 \n 斷行, 
    sMail = "敬啟者:\n" +
            "...\n" + 
            "...\n" + 
            "with regards"
    # SendMail(使用者帳號(寄件人), 收件人列表, 主旨, 信件內容)
    SendMail(username, sMaillist, 'title', sMail)

...
...

if __name__ == "__main__":
    main()