python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python定时发送邮件

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

作者:江上清风山间明月

这篇文章主要介绍了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: 配置电子邮件发送服务

步骤 4: 运行脚本

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

python daily_email_report.py

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

进一步扩展

这样设置后,便可以自动发送每日电子邮件报告了。如果需要部署在服务器上,可以考虑使用 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 * * * * /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定时发送邮件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文