python实现每天定时发送邮件的流程步骤

 更新时间:2024年08月16日 10:05:08   作者:江上清风山间明月  
这篇文章主要介绍了python实现每天定时发送邮件的流程步骤,要编写一个用于自动发送每日电子邮件报告的 Python 脚本,并配置它在每天的特定时间发送电子邮件,文中给大家介绍了详细步骤和示例代码,需要的朋友可以参考下

要编写一个用于自动发送每日电子邮件报告的 Python 脚本,并配置它在每天的特定时间发送电子邮件,使用 smtplib 和 email 库来发送电子邮件,结合 schedule 库来安排任务。以下是详细步骤和示例代码:

步骤 1: 安装所需的库

首先,确保已经安装了必要的 Python 库。打开终端或命令行,运行以下命令来安装库:

pip install schedule

步骤 2: 编写发送电子邮件的 Python 脚本

以下是一个基本的 Python 脚本,它会从 Gmail 账户发送一封带有报告内容的电子邮件。可以根据需要进行修改。

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"

# 发送电子邮件的函数
def send_email():
    # 创建一个MIMEMultipart对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = "每日报告"

    # 邮件正文内容
    body = "这是您的每日报告。"
    msg.attach(MIMEText(body, 'plain'))

    # 登录到邮件服务器并发送邮件
    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("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {e}")
    finally:
        server.quit()

# 设置每天固定时间发送邮件
schedule.every().day.at("08:00").do(send_email)

# 保持脚本运行,检查任务调度
while True:
    schedule.run_pending()
    time.sleep(60)  # 每隔一分钟检查一次任务

步骤 3: 配置电子邮件发送服务

  • Gmail 设置: 如果使用的是 Gmail 发送电子邮件,请确保你的 Google 账户允许 “不太安全的应用访问”(虽然目前 Gmail 已经开始限制这个选项,可以考虑使用 App Passwords 代替)。
  • App Passwords: 对于启用了两步验证的账户,需要为脚本生成一个应用密码,而不是使用你的普通账户密码。
  • 修改脚本: 在 sender_email 和 password 变量中填入你的电子邮件地址和应用密码。

步骤 4: 运行脚本

保存脚本到一个 Python 文件中(如 daily_email_report.py),然后在终端运行:

python daily_email_report.py

脚本将会在每天的早上 08:00 发送一封邮件到指定的收件人邮箱。

进一步扩展

  • 自定义报告内容: 将 body 变量替换为动态生成的报告内容,可以从文件、数据库或 API 获取数据,并格式化成报告。
  • 多收件人: 可以将 receiver_email 改为一个包含多个邮件地址的列表,并在 sendmail 方法中循环发送邮件。

这样设置后,便可以自动发送每日电子邮件报告了。如果需要部署在服务器上,可以考虑使用 nohup 或将其设置为系统服务。

补充知识:Python定时自动发送邮件

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] # 获取当日数据
    # 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)
 
 
    # 发送邮件
    try:
        smtp.sendmail(from_addr= from_email,to_addrs= reciver_email,msg= mm.as_string())
        print('发送成功')
    except smtplib.SMTPException:
        print("发送失败")
 
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、定时调度-使用Linux中的crontab

(1) 进入编辑页面

crontab -e

(2) 编写定时调度语句

  • 测试用:每2分钟调度一次
  • 注意:在anaconda3 中创建了一个名叫study的虚拟环境,并在该环境中运行上述python脚本。关于如何在anaconda中创建虚拟环境,以及pycharm编辑器本地代码如何上传到Linux,可阅读第三部分-补充内容
*/2 * * * * /opt/module/anaconda3/envs/study/bin/python /opt/code/python/sendemail3.py

(3) 重启crontab 使调度配置生效

[root@master ~]# service crond restart

(4) 观察调度进度

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

(5) 查看调度执行日志

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

到此这篇关于python实现每天定时发送邮件的流程步骤的文章就介绍到这了,更多相关python定时发送邮件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅析Python与Mongodb数据库之间的操作方法

    浅析Python与Mongodb数据库之间的操作方法

    这篇文章主要介绍了Python与Mongodb数据库之间的操作,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-07-07
  • 如何使用Python VTK高亮显示actor

    如何使用Python VTK高亮显示actor

    这篇文章主要介绍了如何使用Python VTK高亮显示actor,通过Python-VTK在同一个窗口中,高亮显示选中的actor。本例子中的代码,当窗口中的圆球actor被选中时,会变成红色,并且会显示actor三遍面片边缘信息,下文相关内容需要的小伙伴可以参考一下
    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 线性分类模型的实现

    python SVM 线性分类模型的实现

    这篇文章主要介绍了python SVM 线性分类模型的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python替换Excel表格中的空值或指定值的实现

    Python替换Excel表格中的空值或指定值的实现

    本文介绍了使用Python的pandas库结合openpyxl来批量替换Excel表格中的空值或指定值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • 使用Python实现从零开始打造一个三维绘图系统

    使用Python实现从零开始打造一个三维绘图系统

    这篇文章主要为大家详细介绍了如何使用Python实现一个绘图系统,通过指定x,y,z的表达式,以实现三维绘图的目的,感兴趣的可以了解下
    2024-02-02
  • python入门学习笔记分享

    python入门学习笔记分享

    这篇文章主要介绍了关于Python的一些总结,希望自己以后在学习Python的过程中可以边学习边总结,就自己之前的学习先做以总结,之后将不断总结更新
    2021-10-10
  • pytest使用@pytest.mark.parametrize()实现参数化的示例代码

    pytest使用@pytest.mark.parametrize()实现参数化的示例代码

    这篇文章主要介绍了pytest使用@pytest.mark.parametrize()实现参数化,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • 在Python的Django框架中simple-todo工具的简单使用

    在Python的Django框架中simple-todo工具的简单使用

    这篇文章主要介绍了在Python的Django框架中simple-todo工具的简单使用,该工具基于原web.py中的开源项目,需要的朋友可以参考下
    2015-05-05

最新评论