之前學習過SMTP(Simple Mail Transfer Protocol,知道是簡單郵件傳輸協定,是一組用于由源位址到目的位址傳送郵件的規則,由它來控制信件的中轉方式。
python的smtplib提供了一種很友善的途徑發送電子郵件。它對smtp協定進行了簡單的封裝。
學習一下python對其的操作方法:
Python建立 SMTP 對象文法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
參數說明:
參數 | 說明 |
host | SMTP 伺服器主機 |
port | 如果你提供了 host 參數, 你需要指定 SMTP 服務使用的端口号,一般情況下SMTP端口号為25 |
local_hostname | 如果SMTP在你的本機上,你隻需要指定伺服器位址為 localhost |
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = [‘[email protected]']
message = MIMEText('Python 郵件發送測試...', 'plain', 'utf-8')
message['From'] = Header("菜鳥教程", 'utf-8')
message['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")