如何根据条件向多个收件人发送个性化电子邮件?

问题描述 投票:-1回答:2

我正在制作一个程序,该程序导入具有多个车辆注册信息和车辆所属人员电子邮件的excel文件。该程序使用MOT API搜索MOT数据库,并提取每辆车的MOT上剩余的日期。我设置了一个条件,如果剩余天数少于30天,程序将向该人发送一封电子邮件作为提醒。此刻,我的程序向列表中的所有人发送了通用电子邮件,这些人的MOT在30天内用完了。我想对电子邮件进行个性化设置,类似于以下示例:“您的注册为_______的车辆的MOT将在__天后过期!”

因此,程序将从我的数据框中获取注册信息和剩余的日期,并将其发送给相应的个人。我认为这将需要某种for循环,但是我不确定如何实现它。任何帮助深表感谢。这是我的代码:

apiKey = 'abcdxyz'

import requests
from datetime import datetime
import smtplib
import time
import pandas as pd
import pprint as pp
import xlrd

df = pd.read_excel(r'vehicles.xlsx')  # Reading the excel file with the vehicle database
registrations = df['registration'].tolist()  # Converting the registrations column to a list
mobile = df['mobile'].tolist()  # Converting the mobile numbers column to a list
email = df['email'].tolist()  # Converting the email column to a list
list_days_left = []  # Empty list to store data later


# Function to extract days left on MOT using the given dataframe:
def check_days_left(regi):
    headers = {
        'Accept': 'application/json',
        'x-api-key': apiKey,
    }
    params = (
        ('registration', regi),
    )
    response = requests.get('https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests',
                            headers=headers, params=params)
    r = response.json()  # This returns a list of dicts of the full MOT History data
    carDetails = r[0]  # Access the first dictionary of the list
    motTests = carDetails['motTests']  # This returns a list of dicts again of the MOT tests
    latestTest = motTests[0]  # Access the first dictionary to get the details of the latest test
    expDate = latestTest['expiryDate']  # This returns the expiry date key of the latest test dictionary
    uk_date = datetime.strptime(expDate, '%Y.%m.%d')  # Convert expDate to datetime format
    difference = uk_date - datetime.now()  # Gets the timedelta between now and expiry date
    days_left = difference.days  # Extract the number of days from the above as an int
    return days_left


# Function to apply the above function to each registration in the dataframe and append it to the empty list creater earlier:
def get_days_left():
    for reg in registrations:
        list_days_left.append(check_days_left(reg))
    # print(list_days_left)

    df['days_left'] = list_days_left
    # print(df)

    df.drop(df[df.days_left > 30].index, axis=0, inplace=True)
    print(df)
    return df


# Function to send emails:
def send_mail(m):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()

    server.login('[email protected]', 'mypassword')
    subject = 'Your MOT is expiring soon!'
    body = f"The MOT for your vehicle is running out soon!"
    msg = f'Subject: {subject}\n\n{body}'

    server.sendmail(
        '[email protected]',
        m,
        msg
    )
    print('EMAIL HAS BEEN SENT!')

    server.quit()


# Calling the function to return a dataframe with just those vehicles whose MOT runs out in 30 days:
get_days_left()


# Calling the function to send email to each person on the list:
for mailid in df['email']:
    send_mail(mailid)



python
2个回答
0
投票
在循环内,您将访问所有变量并发送邮件。

0
投票
def get_days_left(): for reg in registrations: days_left = check_days_left(reg) # Assuming days_left is an integer if days_left < 30: send_mail("[email protected]", reg=reg, days_left=days_left) def send_mail(ownerEmail, reg, days_left): # Send the mail here. server.sendmail("[email protected]", ownerEmail, f"Your vehicle with registration: {reg} has {days_left} days left!")

对于任何格式错误,或者如果我的回复不是一流的,我没有在这里发布过,我们深表歉意。编辑:添加了send_mail如何看起来清晰。

© www.soinside.com 2019 - 2024. All rights reserved.