How to Send an Email Using Python
Lecturer: Julie Wang
Date: Apr. 12th, 2020
OUTLINE
-
SMTP
-
Send an Email
-
Reference
SMTP
Simple Mail Transfer Protocol
簡單郵件傳輸協定
Client
Server


建立連線
220
HELO/EHLO
250
LOGIN
235
220/235
傳送郵件
{}
關閉連線
221/451
Send an Email

匯入 smtplib 模組
import smtplib建立 SMTP 安全連線
#SSL
smtpssl=smtplib.SMTP_SSL("smtp.gmail.com", 465)
#TSL
smtp=smtplib.SMTP("smtp.gmail.com", 587)呼叫 ehlo() 向郵件主機註冊身份
#SSL
smtpssl.ehlo()
#TLS
smtp.ehlo()
呼叫 login() 登入郵件主機
#SSL
smtpssl.login("myaccount@gmail.com", "mypassword")
#TLS
smtp.starttls() #啟動 TLS 加密模式
smtp.login("myaccount@gmail.com", "mypassword")呼叫 sendmail() 傳送郵件
sendmail(from_addr, to_addr, msg, mail_options=(), rcpt_options=())- from_addr : 寄件者郵件位址
- to_addr : 收信者郵件位址
- msg : 信件內容
#TLS
smtp.sendmail("mygmail@gmail.com", "myhinetmail@msa.hinet.net", "Subject:Gmail sent by Python scripts\nHello World!")
#SSL
smtpssl.sendmail("mygmail@gmail.com", "myhinetmail@msa.hinet.net", "Subject:Gmail sent by Python scripts\nHello World!")關閉郵件主機連線
#TSL
smtp.quit()
#SSL
smtpssl.quit()完整程式碼
#TLS
import smtplib
smtp = smtplib.SMTP("smtp.gmail.com",587)
smtp.ehlo()
smtp.starttls()
smtp.login("abc@gmail.com","password")
from_addr="abc@gmail.com"
to_addr="abc@gmail.com"
msg="Subject: Gmail send by Python scripts\nhello its me!"
status=smtp.sendmail(from_addr, to_addr, msg)
if status =={}:
print("success")
else:
print("failed")Reference
小狐狸事務所 (2018) . Python 學習筆記 : 以 Gmail 寄送郵件的方法 (一) .Retrieved from https://yhhuang1966.blogspot.com/2018/10/python-gmail.html
Python (2020) . smtplib — SMTP protocol client. Retrieved from https://docs.python.org/3/library/smtplib.html
Ken Chen (2019). Send Gmail with Python. Retrieved form https://medium.com/@ken00535/send-gmail-with-python-7aaa822695d6
Thanks for listening.
How to Send an Email Using Python
By juliewah
How to Send an Email Using Python
SIRLA 108-2 This 15 Speech
- 198