天天看點

每日自動發郵件(Python +QQ郵箱 + Windows 10定時任務)

參考:

​​Python-100-Days/14.網絡程式設計入門和網絡應用開發.md at master · jackfrued/Python-100-Days · GitHub​​

​​什麼是授權碼,它又是如何設定?_QQ郵箱幫助中心​​

一、申請授權碼

每日自動發郵件(Python +QQ郵箱 + Windows 10定時任務)

登陸qq郵箱,設定,賬戶,(往下找)POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務,

開啟服務:POP3/SMTP服務 。手機驗證後得到16位授權碼,複制下來後面要用。

詳情見:​​什麼是授權碼,它又是如何設定?_QQ郵箱幫助中心​​

二、使用SMTP發送郵件

 将下面程式的發件人、收件人、等修改,修改完成後運作即可發送郵件。

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


def main():
    # 請自行修改下面的郵件發送者和接收者
    #【發送者郵箱】
    sender = '[email protected]'
    #【接受者郵箱】
    receivers = ['[email protected]', '[email protected]']
    #【郵件内容】
    message = MIMEText('用Python發送郵件的示例代碼.', 'plain', 'utf-8')
    #【發件人】
    message['From'] = Header('王大錘', 'utf-8')
    #【收件人】
    message['To'] = Header('駱昊', 'utf-8')
    #【郵件主題】
    message['Subject'] = Header('示例代碼實驗郵件', 'utf-8')
    smtper = SMTP('smtp.qq.com')
    #【将secretpass改成自己的16位授權碼】
    smtper.login(sender, 'secretpass')
    smtper.sendmail(sender, receivers, message.as_string())
    print('郵件發送完成!')


if __name__ == '__main__':
    main()      

三、在window中開啟定時任務

四、帶附件的 郵件

from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

import urllib


def main():
    # 建立一個帶附件的郵件消息對象
    message = MIMEMultipart()
    
    # 建立文本内容
    text_content = MIMEText('附件中有本月資料請查收', 'plain', 'utf-8')
    message['Subject'] = Header('本月資料', 'utf-8')
    # 将文本内容添加到郵件消息對象中
    message.attach(text_content)

    # 讀取檔案并将檔案作為附件添加到郵件消息對象中
    with open('/Users/Hao/Desktop/hello.txt', 'rb') as f:
        txt = MIMEText(f.read(), 'base64', 'utf-8')
        txt['Content-Type'] = 'text/plain'
        txt['Content-Disposition'] = 'attachment; filename=hello.txt'
        message.attach(txt)
    # 讀取檔案并将檔案作為附件添加到郵件消息對象中
    with open('/Users/Hao/Desktop/彙總資料.xlsx', 'rb') as f:
        xls = MIMEText(f.read(), 'base64', 'utf-8')
        xls['Content-Type'] = 'application/vnd.ms-excel'
        xls['Content-Disposition'] = 'attachment; filename=month-data.xlsx'
        message.attach(xls)
    
    # 建立SMTP對象
    smtper = SMTP('smtp.126.com')
    # 開啟安全連接配接
    # smtper.starttls()
    sender = '[email protected]'
    receivers = ['[email protected]']
    # 登入到SMTP伺服器
    # 請注意此處不是使用密碼而是郵件用戶端授權碼進行登入
    # 對此有疑問的讀者可以聯系自己使用的郵件伺服器客服
    smtper.login(sender, 'secretpass')
    # 發送郵件
    smtper.sendmail(sender, receivers, message.as_string())
    # 與郵件伺服器斷開連接配接
    smtper.quit()
    print('發送完成!')


if __name__ == '__main__':
    main()