欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)每天定時發(fā)送郵件的流程步驟

 更新時間:2024年08月16日 10:05:08   作者:江上清風山間明月  
這篇文章主要介紹了python實現(xiàn)每天定時發(fā)送郵件的流程步驟,要編寫一個用于自動發(fā)送每日電子郵件報告的 Python 腳本,并配置它在每天的特定時間發(fā)送電子郵件,文中給大家介紹了詳細步驟和示例代碼,需要的朋友可以參考下

要編寫一個用于自動發(fā)送每日電子郵件報告的 Python 腳本,并配置它在每天的特定時間發(fā)送電子郵件,使用 smtplib 和 email 庫來發(fā)送電子郵件,結(jié)合 schedule 庫來安排任務。以下是詳細步驟和示例代碼:

步驟 1: 安裝所需的庫

首先,確保已經(jīng)安裝了必要的 Python 庫。打開終端或命令行,運行以下命令來安裝庫:

pip install schedule

步驟 2: 編寫發(fā)送電子郵件的 Python 腳本

以下是一個基本的 Python 腳本,它會從 Gmail 賬戶發(fā)送一封帶有報告內(nèi)容的電子郵件??梢愿鶕?jù)需要進行修改。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import schedule
import time

# 電子郵件配置信息
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@example.com"
password = "your_password"

# 發(fā)送電子郵件的函數(shù)
def send_email():
    # 創(chuàng)建一個MIMEMultipart對象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = "每日報告"

    # 郵件正文內(nèi)容
    body = "這是您的每日報告。"
    msg.attach(MIMEText(body, 'plain'))

    # 登錄到郵件服務器并發(fā)送郵件
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender_email, password)
        text = msg.as_string()
        server.sendmail(sender_email, receiver_email, text)
        print("郵件發(fā)送成功")
    except Exception as e:
        print(f"郵件發(fā)送失敗: {e}")
    finally:
        server.quit()

# 設置每天固定時間發(fā)送郵件
schedule.every().day.at("08:00").do(send_email)

# 保持腳本運行,檢查任務調(diào)度
while True:
    schedule.run_pending()
    time.sleep(60)  # 每隔一分鐘檢查一次任務

步驟 3: 配置電子郵件發(fā)送服務

  • Gmail 設置: 如果使用的是 Gmail 發(fā)送電子郵件,請確保你的 Google 賬戶允許 “不太安全的應用訪問”(雖然目前 Gmail 已經(jīng)開始限制這個選項,可以考慮使用 App Passwords 代替)。
  • App Passwords: 對于啟用了兩步驗證的賬戶,需要為腳本生成一個應用密碼,而不是使用你的普通賬戶密碼。
  • 修改腳本: 在 sender_email 和 password 變量中填入你的電子郵件地址和應用密碼。

步驟 4: 運行腳本

保存腳本到一個 Python 文件中(如 daily_email_report.py),然后在終端運行:

python daily_email_report.py

腳本將會在每天的早上 08:00 發(fā)送一封郵件到指定的收件人郵箱。

進一步擴展

  • 自定義報告內(nèi)容: 將 body 變量替換為動態(tài)生成的報告內(nèi)容,可以從文件、數(shù)據(jù)庫或 API 獲取數(shù)據(jù),并格式化成報告。
  • 多收件人: 可以將 receiver_email 改為一個包含多個郵件地址的列表,并在 sendmail 方法中循環(huán)發(fā)送郵件。

這樣設置后,便可以自動發(fā)送每日電子郵件報告了。如果需要部署在服務器上,可以考慮使用 nohup 或?qū)⑵湓O置為系統(tǒng)服務。

補充知識:Python定時自動發(fā)送郵件

1、Python代碼

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/6/3 20:37
# @Author  : Maple
# @File    : sendemail.py
 
import smtplib
import email
import datetime
 
from email.mime.text import MIMEText
from email.mime.image import  MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header
import requests
from bs4 import BeautifulSoup
from lxml import etree
import os
 
 
# 獲取當前路徑
current_directory = os.path.dirname(os.path.abspath(__file__))
 
 
# 通過接口獲取城市code
def get_city_code(city):
    response  = requests.get(url="http://toy1.weather.com.cn/search?cityname=" + city)
    res  = response.content.decode('utf-8')
    city_code = eval(res)[0]["ref"].split('~')[0]
    return city_code
 
 
# 通過接口獲取城市天氣
def get_Weather(city_code):
    url = f'http://www.weather.com.cn/weather/{city_code}.shtml'
    req = requests.get(url= url)
    req.encoding = 'utf-8'
    soup = BeautifulSoup(req.text,'html.parser')
    ul_tag = soup.find('ul','t clearfix')
    li_tag = ul_tag.findAll('li')[0] # 獲取當日數(shù)據(jù)
    # print(li_tag)
 
    #獲取氣溫、低溫、高溫和風力
    weather = li_tag.find('p','wea').string
    low_temp =  li_tag.find('p', 'tem').find('i').string if li_tag.find('p', 'tem').find('i') else None
    high_temp = li_tag.find('p','tem').find('span').string if li_tag.find('p', 'tem').find('span') else None
    wind = li_tag.find('p','win').find('i').string
 
    return weather,low_temp,high_temp,wind
 
# 通過接口獲取每日一句
def get_one_sentence():
    get_request = requests.get('https://v.api.aa1.cn/api/yiyan/index.php')
    html = etree.HTML(get_request.text)
    sentence = html.xpath('/html/body/p/text()')[0]
 
    return sentence
 
# 通過接口獲取隨機圖片 
def get_random_pic():
    res = requests.get(url='https://api.thecatapi.com/v1/images/search?size=full')
    print(res.content.decode('utf-8'))
    # pic = res.content.decode('utf-8')[0]['url']
    pic_url = eval(res.content.decode('utf-8'))[0]['url']
    pic_name = pic_url.split('/')[-1]
    pic_id = eval(res.content.decode('utf-8'))[0]['id']
    print(pic_url)
 
    buf = requests.get(pic_url).content
 
    with open(current_directory + '/sources/' + pic_name, 'wb+') as f:
        f.write(buf)
    return pic_name
 
 
def get_email_content(city):
 
    my_date = datetime.datetime.now().strftime('%Y-%m-%d')
 
    city_code = get_city_code(city)
    weather,low_temp,high_temp,wind = get_Weather(city_code)
 
    if low_temp is None or high_temp is None:
        tmp = high_temp if low_temp is None  else low_temp
    else:
        tmp = low_temp + '~' + high_temp
 
    sentense = get_one_sentence()
 
    out_str = "{}\n\n今日日期:{}\n|城市:{}\n|天氣:{}\n|氣溫:{}\n|風力:{}".format(sentense,my_date,city,weather,tmp,wind)
    return out_str
 
 
 
def sendEmail(from_email,reciver_email,content):
 
    user = "353511235@qq.com"
    password = "yqzmyivsrpkvcbae"
 
    # smtp = smtplib.SMTP_SSL("smtp.qq.com", port=587)
    # Linux上只能用SMTP,不知為何,否則會報[SSL: WRONG_VERSION_NUMBER]錯誤
    smtp  = smtplib.SMTP("smtp.qq.com",port=587)
    # 打印與服務器交互信息
    smtp.set_debuglevel(1)
    smtp.login(user= user,password=password)
 
    mm = MIMEMultipart('related')
    mm['From'] = Header('Maple2 <353511235@qq.com>')
    mm['To'] = Header('KK <maplea2012@gmail.com>', 'utf-8')
 
 
    #設置郵件標題
    subject_content = "來自你最好的朋友Maple的每日溫馨祝福"
    mm['Subject'] = Header(subject_content,'utf-8')
 
    # 添加正文文本
    message_text = MIMEText(content, 'plain', 'utf-8')
 
    # 添加圖片-1:專屬頭像
    with open(current_directory + '/sources/頭像.jpg', 'rb') as r:
        img = r.read()
 
    message_img1 = MIMEImage(img)
 
    # 添加圖片-2:隨機圖片
    pic_name = get_random_pic()
    with open(current_directory + '/sources/' + pic_name, 'rb') as r:
        img2= r.read()
 
    message_img2 = MIMEImage(img2)
 
 
    mm.attach(message_text)
    mm.attach(message_img1)
    mm.attach(message_img2)
 
 
    # 發(fā)送郵件
    try:
        smtp.sendmail(from_addr= from_email,to_addrs= reciver_email,msg= mm.as_string())
        print('發(fā)送成功')
    except smtplib.SMTPException:
        print("發(fā)送失敗")
 
if __name__ == '__main__':
 
    city_code = get_city_code('廣州')
    weather, low_temp, high_temp, wind = get_Weather(city_code)
    # print(weather)
    # print(low_temp)
    # print(high_temp)
    # print(wind)
 
    # sentense  = get_one_sentence()
    # print(sentense)
 
    content = get_email_content('廣州')
    print(content)
 
    sendEmail("353511235@qq.com","maplea2012@gmail.com",content)
    # print(city_code)

2、定時調(diào)度-使用Linux中的crontab

(1) 進入編輯頁面

crontab -e

(2) 編寫定時調(diào)度語句

  • 測試用:每2分鐘調(diào)度一次
  • 注意:在anaconda3 中創(chuàng)建了一個名叫study的虛擬環(huán)境,并在該環(huán)境中運行上述python腳本。關于如何在anaconda中創(chuàng)建虛擬環(huán)境,以及pycharm編輯器本地代碼如何上傳到Linux,可閱讀第三部分-補充內(nèi)容
*/2 * * * * /opt/module/anaconda3/envs/study/bin/python /opt/code/python/sendemail3.py

(3) 重啟crontab 使調(diào)度配置生效

[root@master ~]# service crond restart

(4) 觀察調(diào)度進度

[root@master python]# tail -f /var/log/cron

(5) 查看調(diào)度執(zhí)行日志

[root@master python]# vim /var/spool/mail/root

到此這篇關于python實現(xiàn)每天定時發(fā)送郵件的流程步驟的文章就介紹到這了,更多相關python定時發(fā)送郵件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 淺析Python與Mongodb數(shù)據(jù)庫之間的操作方法

    淺析Python與Mongodb數(shù)據(jù)庫之間的操作方法

    這篇文章主要介紹了Python與Mongodb數(shù)據(jù)庫之間的操作,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • 如何使用Python?VTK高亮顯示actor

    如何使用Python?VTK高亮顯示actor

    這篇文章主要介紹了如何使用Python?VTK高亮顯示actor,通過Python-VTK在同一個窗口中,高亮顯示選中的actor。本例子中的代碼,當窗口中的圓球actor被選中時,會變成紅色,并且會顯示actor三遍面片邊緣信息,下文相關內(nèi)容需要的小伙伴可以參考一下
    2022-04-04
  • 解決python pandas讀取excel中多個不同sheet表格存在的問題

    解決python pandas讀取excel中多個不同sheet表格存在的問題

    這篇文章主要介紹了解決python pandas讀取excel中多個不同sheet表格存在的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • 淺談Python處理PDF的方法

    淺談Python處理PDF的方法

    這篇文章主要介紹了Python處理PDF的兩種方法代碼示例,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • python SVM 線性分類模型的實現(xiàn)

    python SVM 線性分類模型的實現(xiàn)

    這篇文章主要介紹了python SVM 線性分類模型的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • Python替換Excel表格中的空值或指定值的實現(xiàn)

    Python替換Excel表格中的空值或指定值的實現(xiàn)

    本文介紹了使用Python的pandas庫結(jié)合openpyxl來批量替換Excel表格中的空值或指定值,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-12-12
  • 使用Python實現(xiàn)從零開始打造一個三維繪圖系統(tǒng)

    使用Python實現(xiàn)從零開始打造一個三維繪圖系統(tǒng)

    這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)一個繪圖系統(tǒng),通過指定x,y,z的表達式,以實現(xiàn)三維繪圖的目的,感興趣的可以了解下
    2024-02-02
  • python入門學習筆記分享

    python入門學習筆記分享

    這篇文章主要介紹了關于Python的一些總結(jié),希望自己以后在學習Python的過程中可以邊學習邊總結(jié),就自己之前的學習先做以總結(jié),之后將不斷總結(jié)更新
    2021-10-10
  • pytest使用@pytest.mark.parametrize()實現(xiàn)參數(shù)化的示例代碼

    pytest使用@pytest.mark.parametrize()實現(xiàn)參數(shù)化的示例代碼

    這篇文章主要介紹了pytest使用@pytest.mark.parametrize()實現(xiàn)參數(shù)化,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • 在Python的Django框架中simple-todo工具的簡單使用

    在Python的Django框架中simple-todo工具的簡單使用

    這篇文章主要介紹了在Python的Django框架中simple-todo工具的簡單使用,該工具基于原web.py中的開源項目,需要的朋友可以參考下
    2015-05-05

最新評論