如何使用python从熊猫数据框中将电子邮件发送到具有不同主题的不同收件人地址
Posted
技术标签:
【中文标题】如何使用python从熊猫数据框中将电子邮件发送到具有不同主题的不同收件人地址【英文标题】:How to send emails to different reciver address with different subject from a pandas dataframe using python 【发布时间】:2020-10-12 16:22:33 【问题描述】:我在df
下方有我喜欢的数据框。我想发送一封具有独特主题的自动独特电子邮件。
我不确定如何迭代主题行和接收者地址。你能看看我的代码吗?
Name Invoice_Number Invoice_Date Currency Amount Email_Address
Ali 23456 2020-06-11 GBP 200 Ali@gmail.com
Charly 6789 2020-05-12 Euro 600 Charly@hotmail.com
Tom 7823 2020-06-18 Euro 400 Tom@gmail.com
Chang 8950 2020-04-13 SGD 600 Chang@yahoo.com
David 8934 2020-06-16 USD 500 NaN
Mia 78909 2019-12-23 GBP 600 Mia@gmail.com
主题
主题:[Name] / REJECTED Invoice [Invoice_Number] Dated [Invoice_Date] Amount [Currency + Amount]
示例:Ali/ REJECTED Invoice [23456 ] Dated [2020-06-11] Amount [GBP+ 200]
如何做到这一点。
我的代码
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import date
import os
import boto3
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, COMMASPACE
dict1 = "Non-empty": 'receiver': df[Email_Address],
"mail_content":''' Invoice is inncorect''' ,
"Empty": "receiver": 'address_not_found@gmail.com',
"mail_content":" No data Found "
receiver_address = ""
mail_content = ""
if data1['email'].isnull:
receiver_address = dict1["Empty"]["receiver"]
mail_content = dict1["Empty"]["mail_content"]
else:
receiver_address = dict1["Non-empty"]["receiver"]
mail_content = dict1["Non-empty"]["mail_content"]
def create_message(send_from, send_to, subject,plain_text_body):
message = MIMEMultipart('alternative')
message['From'] = send_from
message['To'] = COMMASPACE.join(send_to)
message['Subject'] = subject
message.attach(MIMEText(plain_text_body, 'plain'))
return message
def send_message(message):
client = boto3.client("ses",region_name='eu-west-1')
response = client.send_raw_email(RawMessage = 'Data': message.as_string())
message = create_message(sender_address,[receiver_address ],subject,mail_content)
send_message(message)
【问题讨论】:
【参考方案1】:因此,您可以为 DataFrame 中的所有这些行生成主题行的一种方法是创建一个新列,该列是从 DataFrame 中的其他列构建的构造字符串:
import pandas as pd
df = pd.DataFrame(dict(
Name = ['A','B'],
Invoice_Number = [1,2],
Invoice_Date = ['2020-06-11','2020-05-12'],
Currency = ['GBP','Euro'],
Amount = [200, 600],
Email_Address = ['A@email.com','B@emial.com'],
))
df['Subject'] = (
"["+
df['Name']+
"] / REJECTED Invoice ["+
df['Invoice_Number'].astype(str)+
"] Dated ["+
df['Invoice_Date']+
"] Amount ["+
df['Currency']+
df['Amount'].astype(str)+
"]"
)
print( df['Subject'].values)
现在您已经准备好用于所有电子邮件的主题行了。
Example Code in python Tutor
编辑:OP 提出了后续问题:
@PhillyCaluse89,如何将此值传递给
send_email
函数
我想你可以遍历 df.values 并像这样发送每条消息:
import boto3
import pandas as pd
# I get an import error with `from email.utils import formatdate, COMMASPACE`
# I think this should be a constant not an import
# COMMASPACE = ", "
# I don't think you need this at all though, since you appear to want to send the emails to individual recipients.
# SENDER_ADDRESS might be a good constant to have though
SENDER_ADDRESS = "youremail@email.com"
# Moved all functions to the top of the script
# I don't think you need to use email imports, so try cutting it down to just one send_message function
def send_message(send_from, send_to, subject, plain_text_body):
client = boto3.client("ses", region_name='eu-west-1')
response = client.send_email(
Destination=
'BccAddresses': [
],
'CcAddresses': [
],
'ToAddresses': [
send_to
],
,
Message=
'Body':
'Text':
'Charset': 'UTF-8',
'Data': plain_text_body,
,
,
'Subject':
'Charset': 'UTF-8',
'Data': subject,
,
,
ReplyToAddresses=[
],
ReturnPath='',
ReturnPathArn='',
Source=send_from,
SourceArn='',
)
print(response)
# Adding a test df
df = pd.DataFrame(dict(
Name=['A', 'B'],
Invoice_Number=[1, 2],
Invoice_Date=['2020-06-11', '2020-05-12'],
Currency=['GBP', 'Euro'],
Amount=[200, 600],
Email_Address=['A@email.com', 'B@emial.com'],
))
# Adding a new column to the df containing the constructed subject line string:
df['Subject'] = (
"[" +
df['Name'] +
"] / REJECTED Invoice [" +
df['Invoice_Number'].astype(str) +
"] Dated [" +
df['Invoice_Date'] +
"] Amount [" +
df['Currency'] +
df['Amount'].astype(str) +
"]"
)
# Start a loop through the df.values (Ensure the variables you unpack df.values into match the order of your columns:
for email, subject in df[['Email_Address', 'Subject']].values:
#Not sure why you need that dict, seemed a bit overkill to me, could just do:
if email and not pd.isna(email):
receiver_address = email
mail_content = ''' Invoice is inncorect'''
else:
receiver_address = 'address_not_found@gmail.com'
mail_content = " No data Found "
#calling the function with these params should work if I'm undersanding the docs correctly
send_message(SENDER_ADDRESS, receiver_address, subject, mail_content)
但这都是基于浏览您在后续评论中链接到我的文档的推测。我肯定会在这里忽略一些东西。
【讨论】:
@PhillyCaluse89,如何将此值传递给`send_email`函数 @Ria Alves 我对我的答案进行了编辑。也许会有所帮助?我真的不熟悉用于发送电子邮件的库。 我正在使用https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ses.html#SES.Client.send_email
一个由 AWS 发送库的电子邮件
@PhillyCaluse89,我已经添加了 libabries 。看我帖子的编辑
@Ria Alves 在浏览了您链接到的文档后,我对我的编辑进行了另一次编辑。如果这不能帮助您找到解决方案,那么您可能需要重新表述这个问题,以便更多地关注如何使用该库。这个措辞的方式使您似乎只需要帮助使用来自 pandas.DataFrame
的值创建主题行。以上是关于如何使用python从熊猫数据框中将电子邮件发送到具有不同主题的不同收件人地址的主要内容,如果未能解决你的问题,请参考以下文章