smtplib


  • 引入套件
import smtplib
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
  • 為了連接gmail提供給我們的server我們需要先宣告待會要連到哪個host & port
smtp_ssl_host = 'smtp.gmail.com'
smtp_ssl_port = 465
  • 以及寄送mail需要登入的帳號密碼
username = '[email protected]'
password = getpass.getpass() # 將密碼馬賽克起來

  • 指定寄件者與收件者,寄件者為string,收件者為list
email_from = '[email protected]'
email_to = ['[email protected]']
  • 這封mail的標題與內文
email_subject = 'Gmail 自動信件測試'
email_body = '''嗨

本信為自動發送

請勿回覆
'''
  • 使用MIMEMultipart()創造一個msg物件,並把標題、寄件者、收件者附加上去
msg = MIMEMultipart()
msg['Subject'] = email_subject
msg['From'] = email_from
msg['To'] = ', '.join(email_to)
  • 使用MIMEText()把內文轉成mail接受的格式並使用attach加到msg上
txt = MIMEText(email_body)
msg.attach(txt)
  • 連線server、登入、寄出、登出
server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
server.login(username, password)
server.sendmail(email_from, email_to, msg.as_string())
server.quit()

results matching ""

    No results matching ""