smtp

如何用python寄gmail

寄信者的google帳號需啟動低安全性應用程式存取權 (google帳戶 -> 登入和安全性 -> 具有帳戶存取權的應用程式)

如果有設定雙驗證則無法開啟上述存取權,建議可以直接開個新google帳號

若建立smtplib.SMTP_SSL連線時完全無回應的話可能與網路環境有關(在公司網路不行,筆電+手機網路就可以惹)

import smtplib
from email.mime.text import MIMEText

gmail_user = '123@gmail.com' # 寄信者
gmail_password = '123' # 寄信者密碼

msg = MIMEText('content')  # 信件內容
msg['Subject'] = 'Test'  # 信件標題
msg['From'] = gmail_user  # 寄信者
msg['To'] = '456@gmail.com'  # 收信者

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)  # 不要亂改ㄛ
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, '456@gmail.com', msg.as_string())
server.quit()

print('Email sent!')

也可把SMTP_SSL改成SMTP連線,但就要調整其他設定惹還沒試成功

參考連結: smtp_ssl https://amoshyc.github.io/blog/2018/sending-gmail-in-python.html#注意事項

smtp https://self.jxtsai.info/2016/09/python_22.html

附加檔案

from email.mime.text import MIMEText

filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)           
msg.attach(attachment)

https://codeday.me/bug/20180210/131030.html

Last updated