最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

要編寫一個(gè)用于自動(dòng)發(fā)送每日電子郵件報(bào)告的 Python 腳本,并配置它在每天的特定時(shí)間發(fā)送電子郵件,使用 smtplib 和 email 庫(kù)來(lái)發(fā)送電子郵件,結(jié)合 schedule 庫(kù)來(lái)安排任務(wù)。以下是詳細(xì)步驟和示例代碼:

步驟 1: 安裝所需的庫(kù)

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

pip install schedule

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

以下是一個(gè)基本的 Python 腳本,它會(huì)從 Gmail 賬戶發(fā)送一封帶有報(bào)告內(nèi)容的電子郵件。可以根據(jù)需要進(jìn)行修改。

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)建一個(gè)MIMEMultipart對(duì)象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = "每日?qǐng)?bào)告"

    # 郵件正文內(nèi)容
    body = "這是您的每日?qǐng)?bào)告。"
    msg.attach(MIMEText(body, 'plain'))

    # 登錄到郵件服務(wù)器并發(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()

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

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

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

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

步驟 4: 運(yùn)行腳本

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

python daily_email_report.py

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

進(jìn)一步擴(kuò)展

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

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

補(bǔ)充知識(shí):Python定時(shí)自動(dòng)發(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
 
 
# 獲取當(dāng)前路徑
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] # 獲取當(dāng)日數(shù)據(jù)
    # print(li_tag)
 
    #獲取氣溫、低溫、高溫和風(fēng)力
    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
 
# 通過接口獲取隨機(jī)圖片 
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|風(fēng)力:{}".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,不知為何,否則會(huì)報(bào)[SSL: WRONG_VERSION_NUMBER]錯(cuò)誤
    smtp  = smtplib.SMTP("smtp.qq.com",port=587)
    # 打印與服務(wù)器交互信息
    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')
 
 
    #設(shè)置郵件標(biāo)題
    subject_content = "來(lái)自你最好的朋友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:隨機(jī)圖片
    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、定時(shí)調(diào)度-使用Linux中的crontab

(1) 進(jìn)入編輯頁(yè)面

crontab -e

(2) 編寫定時(shí)調(diào)度語(yǔ)句

  • 測(cè)試用:每2分鐘調(diào)度一次
  • 注意:在anaconda3 中創(chuàng)建了一個(gè)名叫study的虛擬環(huán)境,并在該環(huán)境中運(yùn)行上述python腳本。關(guān)于如何在anaconda中創(chuàng)建虛擬環(huán)境,以及pycharm編輯器本地代碼如何上傳到Linux,可閱讀第三部分-補(bǔ)充內(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)度進(jìn)度

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

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

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

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

相關(guān)文章

  • Python?queue模塊功能大全

    Python?queue模塊功能大全

    queue模塊是Python內(nèi)置的標(biāo)準(zhǔn)模塊,可以直接通過import?queue引用,這篇文章主要介紹了Python?queue模塊都具有哪些功能,需要的朋友可以參考下
    2023-04-04
  • 基于python不同開根號(hào)的速度對(duì)比分析

    基于python不同開根號(hào)的速度對(duì)比分析

    這篇文章主要介紹了基于python不同開根號(hào)的速度對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2021-03-03
  • 基于python實(shí)現(xiàn)對(duì)文件進(jìn)行切分行

    基于python實(shí)現(xiàn)對(duì)文件進(jìn)行切分行

    這篇文章主要介紹了基于python實(shí)現(xiàn)對(duì)文件進(jìn)行切分行,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • python 遠(yuǎn)程統(tǒng)計(jì)文件代碼分享

    python 遠(yuǎn)程統(tǒng)計(jì)文件代碼分享

    享一個(gè)Python獲取遠(yuǎn)程文件大小的函數(shù)代碼,簡(jiǎn)單實(shí)用,是學(xué)習(xí)Python編程的基礎(chǔ)實(shí)例。
    2015-05-05
  • opencv3/C++實(shí)現(xiàn)視頻背景去除建模(BSM)

    opencv3/C++實(shí)現(xiàn)視頻背景去除建模(BSM)

    今天小編就為大家分享一篇opencv3/C++實(shí)現(xiàn)視頻背景去除建模(BSM),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2019-12-12
  • Python中二進(jìn)制、八進(jìn)制與十六進(jìn)制高級(jí)操作指南

    Python中二進(jìn)制、八進(jìn)制與十六進(jìn)制高級(jí)操作指南

    在現(xiàn)代計(jì)算領(lǐng)域,直接操作不同進(jìn)制的數(shù)值是一項(xiàng)核心技術(shù)能力,Python提供了強(qiáng)大靈活的進(jìn)制操作工具鏈,下面我們就來(lái)看看Python處理進(jìn)制數(shù)據(jù)的詳細(xì)方法吧
    2025-08-08
  • 通過python掃描二維碼/條形碼并打印數(shù)據(jù)

    通過python掃描二維碼/條形碼并打印數(shù)據(jù)

    這篇文章主要介紹了通過python掃描二維碼/條形碼并打印數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • python3爬取淘寶信息代碼分析

    python3爬取淘寶信息代碼分析

    本篇文章通過代碼實(shí)例給大家分享了python3爬取淘寶信息的過程以及實(shí)例分析,對(duì)此有興趣的朋友學(xué)習(xí)下。
    2018-02-02
  • Python實(shí)現(xiàn)的批量修改文件后綴名操作示例

    Python實(shí)現(xiàn)的批量修改文件后綴名操作示例

    這篇文章主要介紹了Python實(shí)現(xiàn)的批量修改文件后綴名操作,涉及Python目錄文件的遍歷、重命名等相關(guān)操作技巧,需要的朋友可以參考下
    2018-12-12
  • python元組和字典的內(nèi)建函數(shù)實(shí)例詳解

    python元組和字典的內(nèi)建函數(shù)實(shí)例詳解

    這篇文章主要介紹了python元組和字典的內(nèi)建函數(shù),結(jié)合實(shí)例形式詳細(xì)分析了Python元組和字典的各種常見內(nèi)建函數(shù)功能與相關(guān)使用技巧,需要的朋友可以參考下
    2019-10-10

最新評(píng)論

玉门市| 田东县| 新源县| 柳江县| 华安县| 宁明县| 鹤壁市| 锡林郭勒盟| 康乐县| 宣威市| 文水县| 宝丰县| 南通市| 永清县| 防城港市| 涡阳县| 康平县| 平舆县| 沧源| 黎川县| 佛教| 赤水市| 正蓝旗| 太和县| 赫章县| 拉孜县| 体育| 昌图县| 鄂托克旗| 乌拉特前旗| 陵川县| 句容市| 中阳县| 白银市| 武清区| 宽城| 土默特左旗| 光山县| 新营市| 阿合奇县| 沁源县|