1. 程式人生 > >Python郵件發送腳本(Linux,Windows)通用

Python郵件發送腳本(Linux,Windows)通用

end bject from mage 郵箱 lin python tex div

腳本

#!/usr/bin/python
#-*- coding:utf-8 -*-
#Python Mail for chenglee
#if fileformat=dos, update fileformat=unix
#code:set fileformat=unix
#check:set ff ?
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

my_sender=‘[email protected]‘    # 發件人郵箱賬號
my_pass = ‘xxxxxxxxxxx‘              # 發件人郵箱密碼(當時申請smtp給的口令)
my_user=‘[email protected]‘      # 收件人郵箱賬號,我這邊發送給自己
def mail():
    ret=True
    try:
        msg=MIMEText(‘11填寫郵件內容‘,‘plain‘,‘utf-8‘)
        msg[‘From‘]=formataddr(["發件人昵稱",my_sender])  # 括號裏的對應發件人郵箱昵稱、發件人郵箱賬號
        msg[‘To‘]=formataddr(["收件人昵稱",my_user])              # 括號裏的對應收件人郵箱昵稱、收件人郵箱賬號
        msg[‘Subject‘]="11郵件主題-測試"                # 郵件的主題,也可以說是標題

        server=smtplib.SMTP_SSL("smtp.qq.com", 465)  # 發件人郵箱中的SMTP服務器,端口是465
        server.login(my_sender, my_pass)  # 括號中對應的是發件人郵箱賬號、郵箱密碼
        server.sendmail(my_sender,[my_user,],msg.as_string())  # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
        server.quit()# 關閉連接
    except Exception:# 如果 try 中的語句沒有執行,則會執行下面的 ret=False
        ret=False
    return ret

ret=mail()
if ret:
    print("郵件發送成功")
else:
    print("郵件發送失敗")  

在windows下用的時候,前兩行可去可留!

測試結果

windows

技術分享圖片

技術分享圖片

linux

技術分享圖片

技術分享圖片

提示

作為發送人, 需要開啟兩項服務。

技術分享圖片

Python郵件發送腳本(Linux,Windows)通用