2024 Python-Flask框架:网页版 邮件超时自动提醒器(超简单)

首先安装flask框架

pip install flask
pip install pywin32
pip install pandas
pip install datetime

然后根目录下,创建 app.py 和 templates文件夹

(注意我们的原时间是年,周,日的计算方式)

from flask import Flask, render_template, request, redirect, url_for
import pythoncom
import pandas as pd
import win32com.client as win32
from datetime import datetime

app = Flask(__name__)


def get_outlook_email():
    """Get the user's Outlook email address"""
    pythoncom.CoInitializeEx(0)  # Initialize the COM library in the current thread
    outlook = win32.Dispatch('Outlook.Application').GetNamespace('MAPI')
    for account in outlook.Accounts:
        if account.DeliveryStore:
            return account.DeliveryStore.DisplayName
    return None

def send_emails(file_path):
    """Send emails with the selected file as an attachment"""
    if not file_path:
        return

    try:
        pythoncom.CoInitializeEx(0)  # Initialize the COM library in the current thread
        # ... (rest of the send_emails function remains the same)

        # Function to convert the "yearweek.day" format to a datetime object
        def year_week_day_to_date(year_week_day):
            try:
                year = int(str(year_week_day)[:2]) + 2000  # Assuming 2000 as the base year
                week = int(str(year_week_day)[2:4])
                day = int(str(year_week_day)[-1])

                # Check if the week number is valid
                if not (1 <= week <= 53):
                    raise ValueError("Invalid week number")
                date = datetime.strptime(f'{year} {week} {day}', '%Y %W %w')
                return date
            except ValueError as e:
                print(f"Error converting {year_week_day}: {e}")
                return None

        # Get the current date
        current_date = datetime.now()

        # Convert the current date to "year.week.day" format
        current_year = current_date.isocalendar()[0]
        current_week = current_date.isocalendar()[1]
        current_day = current_date.isocalendar()[2]
        current_date_format = f"{current_year}{current_week:02d}{current_day}"

        # Open Outlook and call the API
        outlook = win32.Dispatch('Outlook.Application')

        df['Name'] = df['Name'].astype(str)  # Convert the 'Name' column to string data type

        # Check dates and send emails
        for index, row in df.iterrows():
            prognosetermine = row['过期时间']
            full_name = row['英文名']

            # Check if the 'Name' column is empty
            if pd.isna(full_name) or full_name.strip() == '':
                print(f"Row {index}: Name is empty, skipping...")
                continue

            # Convert the full name to email format
            name_parts = full_name.split()
            email_name = ''
            if len(name_parts) >= 2:
                first_name, last_name = name_parts[0], name_parts[-1]
                email_name = f'{first_name.lower()}.{last_name.lower()}'

            to_email = f'{email_name}@outlook.com'

            prognose_date = year_week_day_to_date(prognosetermine)

            if prognose_date is not None and current_date > prognose_date:
                # Create and send the email
                mail_item = outlook.CreateItem(0)
                mail_item.Subject = "超时提醒"
                mail_item.BodyFormat = 1
                mail_item.Body = f"""
你好 {full_name}, 你已经超时!
"""
                mail_item.To = to_email
                attachment = mail_item.Attachments.Add(file_path)
                mail_item.Send()

    except Exception as e:
        print(f"Error sending emails: {e}")

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file_path = request.form.get('file_path')
        send_emails(file_path)
        return redirect(url_for('index'))

    email_address = get_outlook_email()
    return render_template('index.html', email_address=email_address)

if __name__ == '__main__':
    app.run(debug=True)

最后在templates文件夹下创建/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Email with Attachment</title>
</head>
<body>
    <h1>Email with Attachment</h1>
    <p>Your Outlook email address: {{ email_address }}</p>
    <form method="post" enctype="multipart/form-data">
        <label for="file_path">Select File:</label>
        <input type="file" id="file_path" name="file_path" required>
        <button type="submit">Send Email</button>
    </form>
</body>
</html>

在vscode中点击执行后:

点击这个url就可以了

打开后有个简单的web页面:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值