python 爱心邮件代码

python 复制代码
import smtplib
import time
from email.mime.text import MIMEText
import requests
from lxml import etree
import datetime
from requests.exceptions import RequestException

# 邮件配置
sender_maile = ''  # 发件人地址
sender_pass = ''  # 邮件授权码
boy_name = ''  # 发件人姓名
girl_name = ''  # 收件人姓名
receiver_mail = ''  # 收件人邮箱
special_day = '2023-10-11'  # 纪念日
province = 'guangxi'  # 省份
city = 'jiangnan-district'  # 城市
title = ''  # 邮件主题

# 请求头
header = {
    'Referer': 'https://tianqi.moji.com/weather/china/guangxi',
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
}
session = requests.session()

# 获取纪念日距今天数
def get_day():
    d1 = datetime.datetime.strptime(special_day, '%Y-%m-%d')
    d2 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    delta = d2 - d1
    return delta.days

# 获取土味情话
def get_chp():
    url = "https://api.lovelive.tools/api/SweetNothings"
    try:
        resp = requests.get(url=url, verify=True)
        return resp.text
    except RequestException:
        return "获取土味情话失败"

# 获取天气提醒
def get_weathertip():
    try:
        url = f'https://tianqi.moji.com/weather/china/{province}/{city}'
        resp = session.get(url=url, headers=header, verify=False)
        html = etree.HTML(resp.text)
        em = html.xpath('/html/body/div[4]/div[1]/div[4]/em/text()')[0]
        return em
    except:
        return "获取天气提醒失败"

# 获取天气信息
def get_weather():
    try:
        url = f'https://tianqi.moji.com/weather/china/{province}/{city}'
        resp = session.get(url=url, headers=header, verify=False)
        html = ''
        htmls = etree.HTML(resp.text)
        ul = htmls.xpath('/html/body/div[5]/div[1]/div[1]/ul')
        for lis in ul:
            day = lis.xpath('./li[1]/a/text()')[0]
            src = lis.xpath('./li[2]/span/img/@src')[0]
            temperature = lis.xpath('./li[3]/text()')[0]
            air = lis.xpath('./li[5]/strong/text()')[0].strip()
            color = str(lis.xpath('./li[5]/strong/@class')[0])
            color = {
                'level_1': '#8fc31f',
                'level_2': '#d7af0e',
                'level_3': '#f39800',
                'level_4': '#e2361a',
                'level_5': '#5f52a0',
                'level_6': '#631541'
            }.get(color, '#000000')

            html += f"""<div style="display: flex;margin-top:5px;height: 30px;line-height: 30px;justify-content: space-around;align-items: center;">
            <span style="width:15%; text-align:center;">{day}</span>
            <div style="width:10%; text-align:center;">
                <img style="height:26px;vertical-align:middle;" src='{src}' alt="">
            </div>
            <span style="width:25%; text-align:center;">{temperature}</span>
            <div style="width:35%; ">
                <span style="display:inline-block;padding:0 8px;line-height:25px;color:{color}; border-radius:15px; text-align:center;">{air}</span>
            </div>
            </div>"""
        return html
    except:
        return "获取天气失败"

# 获取每日图片
def get_image():
    url = "http://wufazhuce.com/"
    try:
        resp = requests.get(url=url)
        html = etree.HTML(resp.text)
        img_url = html.xpath('//*[@id="carousel-one"]/div/div[1]/a/img/@src')[0]
        return img_url
    except:
        return "https://example.com/default-image.jpg"  # 替换为默认图片链接

# 获取当天日期
def get_today():
    i = datetime.datetime.now()
    date = f"{i.year}/{i.month}/{i.day}"
    return date

# 邮件内容
mail_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body style="margin:0;padding:0;">
    <div style="width:100%; margin: 40px auto;font-size:20px; color:#5f5e5e;text-align:center">
        <span>今天是我们在一起的第</span>
        <span style="font-size:24px;color:rgb(221, 73, 73)">{get_day()}</span>
        <span>天</span>
    </div>
    <div style="width:100%; margin: 0 auto;color:#5f5e5e;text-align:center">
        <span style="display:block;color:#676767;font-size:20px">{get_chp()}</span>
        <br>
        <span style="display:block;color:#676767;font-size:20px">{get_weathertip()}</span>
        <span style="display:block;margin-top:15px;color:#676767;font-size:15px">近期天气预报</span>
        {get_weather()}
    </div>
    <div style="text-align:center;margin:35px 0;">
        <span style="display:block;margin-top:55px;color:#676767;font-size:15px">{boy_name} ❤️ {girl_name}</span>
        <span style="display:block;margin-top:25px;font-size:22px; color:#9d9d9d;">{get_today()}</span>
         <img src='{get_image()}' style="width:100%;margin-top:10px;" alt="">
    </div>
</body>
</html>"""

# 发送邮件
def send_mail():
    try:
        maile_obj = smtplib.SMTP_SSL('smtp.qq.com', 465)
        maile_obj.login(sender_maile, sender_pass)
        msg = MIMEText(mail_content, _subtype='html', _charset='utf-8')
        msg['Subject'] = title
        msg['From'] = f"{boy_name} <{sender_maile}>"
        msg['To'] = f"{girl_name} <{receiver_mail}>"
        maile_obj.sendmail(sender_maile, receiver_mail, msg.as_string())
        maile_obj.quit()
        print("发送成功!")
    except smtplib.SMTPException as e:
        print("邮件发送失败:", e)


if __name__ == '__main__':
    send_mail()
    print("当前时间:", datetime.datetime.now())
相关推荐
Fcy64816 小时前
C++ set&&map的模拟实现
开发语言·c++·stl
叫我:松哥16 小时前
基于大数据和深度学习的智能空气质量监测与预测平台,采用Spark数据预处理,利用TensorFlow构建LSTM深度学习模型
大数据·python·深度学习·机器学习·spark·flask·lstm
你怎么知道我是队长1 天前
C语言---枚举变量
c语言·开发语言
李慕婉学姐1 天前
【开题答辩过程】以《基于JAVA的校园即时配送系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·开发语言·数据库
吃茄子的猫1 天前
quecpython中&的具体含义和使用场景
开发语言·python
じ☆冷颜〃1 天前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
云栖梦泽1 天前
易语言中小微企业Windows桌面端IoT监控与控制
开发语言
数据大魔方1 天前
【期货量化实战】日内动量策略:顺势而为的短线交易法(Python源码)
开发语言·数据库·python·mysql·算法·github·程序员创富
APIshop1 天前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨1 天前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai