1. 程式人生 > 實用技巧 >python學習-傳送郵件(smtp)

python學習-傳送郵件(smtp)

1. 之前學習過用呼叫第三方模組yagmail來發送郵件,今天又學習了下,用python自帶smtplib來發送郵件

前言:

SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。

python的smtplib提供了一種很方便的途徑傳送電子郵件。它對smtp協議進行了簡單的封裝。

參考程式碼:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服務
mail_host = "smtp.qq.com" # 設定伺服器 mail_user = '[email protected]' # 使用者名稱 mail_pass = "5546654" # 口令 sender = [email protected]' receivers = ['[email protected]', '[email protected]'] # 接收郵件,可設定為你的163郵箱或者其他郵箱 message = MIMEText('Python 郵件傳送測試...', 'plain', 'utf-8') message['From'] = Header(sender, '
utf-8') message['To'] = Header(receivers, 'utf-8') subject = '我的第一封郵件' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 為 SMTP 埠號 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string())
print("郵件傳送成功") except smtplib.SMTPException: print("Error: 無法傳送郵件")

使用Python傳送HTML格式的郵件

Python傳送HTML格式的郵件與傳送純文字訊息的郵件不同之處就是將MIMEText中_subtype設定為html。具體程式碼如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服務
mail_host = "smtp.qq.com"  # 設定伺服器
mail_user = '[email protected]'  # 使用者名稱
mail_pass = "5546654"  # 口令

sender = [email protected]'
receivers = ['[email protected]', '[email protected]']  # 接收郵件,可設定為你的163郵箱或者其他郵箱
mail_msg = """
<p>Python 郵件傳送測試...</p>
<p>這是我的第一次操作</p>
<p><a href="http://www.runoob.com">這是一個連結</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(','.join(receivers))

subject = '我的第一封郵件'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 為 SMTP 埠號
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("郵件傳送成功")
except smtplib.SMTPException:
    print("Error: 無法傳送郵件")

參考連結:https://www.runoob.com/python3/python3-smtp.html