Python郵件激活碼發送

Python郵件激活碼發送,其實很簡單 , Python自帶相應的庫,直接導入庫然後調用就可以,輕鬆加愉快!記住qq需要去設置,才能正常發送!

  • 簡介:
    • 郵件服務器、賬戶、密碼
    • 相關協議:SMTP、POP3、IMAP
    • 默認TCP協議端口:25
  • 用途:經常用在一個網站的註冊激活、通知、找回密碼等場景
  • 庫:smtplib
  • 示例:
import os
import smtplib
# 用於郵件發送的類
from email.mime.text import MIMEText

# 郵箱服務器,這裏依163爲例
mail_server = 'smtp.163.com'

# 用戶名
mail_user = '[email protected]'

# 密碼或授權碼
# 爲了密碼不對外公開,可以通過環境變量進行獲取
# mail_pwd = os.getenv('MAIL_PASSWORD', '123456')
mail_pwd = 'YOU_PASSWORD'
# 消息內容
content = '請點擊右邊鏈接完成激活,激活'

# 創建消息對象,並設置內容,
# 第二個用於指定文本內容類型,若不指定默認是文本
message = MIMEText(content, 'html')

# 設置主題
message['Subject'] = '賬戶激活'

# 設置發送者
message['From'] = mail_user

# 創建郵件發送類
mail = smtplib.SMTP(mail_server, 25)

# 身份認證
mail.login(mail_user, mail_pwd)

# 指定接收者,多個接收者使用列表
to = '[email protected]'

# 發送郵件
mail.sendmail(mail_user, to, message.as_string())

# 結束
mail.quit()
  • 總結:
    • 郵箱服務器配置
    • 創建用於發送的消息對象MIMEText
    • 創建用於發送郵件的對象smtplib.SMTP
    • 使用郵件發送對象發送消息對象
      另外還可這樣:
import smtplib
from email.mime.text import MIMEText

# ----------1.跟發件相關的參數------
smtpserver = "smtp.163.com"            # 發件服務器
port = 0                                            # 端口
sender = "[email protected]"                # 賬號
psw = "**************"                         # 密碼
receiver = "[email protected]"        # 接收人


# ----------2.編輯郵件的內容------
subject = "這個是主題163"
body = '<p>這個是發送的163郵件</p>'  # 定義郵件正文爲html格式
msg = MIMEText(body, "html", "utf-8")
msg['from'] = sender
msg['to'] = "[email protected]"
msg['subject'] = subject

# ----------3.發送郵件------
smtp = smtplib.SMTP()
smtp.connect(smtpserver)                                  # 連服務器
smtp.login(sender, psw)                                     # 登錄
smtp.sendmail(sender, receiver, msg.as_string())  # 發送
smtp.quit()                                                         # 關閉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章