开发者

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

开发者 https://www.devze.com 2024-08-17 09:18 出处:网络 作者: 江上清风山间明月
目录步骤 1: 安装所需的库步骤 2: 编写发送电http://www.devze.com子邮件的 python 脚本步骤 3: 配置电子邮件发送服务步骤 4: 运行脚本进一步扩展补充知识:Python定时自动发送邮件1、Python代码2、定时调度-使用lin
目录
  • 步骤 1: 安装所需的库
  • 步骤 2: 编写发送电http://www.devze.com子邮件的 python 脚本
  • 步骤 3: 配置电子邮件发送服务
  • 步骤 4: 运行脚本
  • 进一步扩展
  • 补充知识:Python定时自动发送邮件
    • 1、Python代码
    • 2、定时调度-使用linux中的crontab
      • (1) 进入编辑页面
      • (2) 编写定时调度语句
      • (3) 重启crontab 使调度配置生效
      • (4) 观察调度进度
      • (5) 查看调度执行日志

要编写一个用于自动发送每日电子邮件报告的 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 rest编程客栈art

(4) 观察调度进度

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

(5) 查看调度执行日志

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号