考虑拥有三个电子邮件 ID
[email protected]
、[email protected]
和 [email protected]
,我为每个用户准备了三个唯一的文件 user1.xlsx
、user2.xlsx
和 user3.xlsx
。我必须向每个用户发送一封电子邮件,并将他们的文件作为附件。
目前,我正在循环发送电子邮件,我认为这不是最佳解决方案。这是电子邮件发送片段的简化版本。
for user, attachment_file in zip(users, attachment_files):
message = Mail(from_email=from_email, to_emails=user)
attachment = Attachment(attachment_file)
message.attachment = [attachment]
send_grid_client.send(message)
有没有办法将这些带有附件的电子邮件作为单个 sendgrid API 调用发送?
您可以使用 Sendgrid Personalizations (https://docs.sendgrid.com/for-developers/sending-email/personalizations) 为每个收件人定义元数据(即 to_email、附件),然后通过一次调用发送
/v3/mail/send
带有个性化数组的 api。像这样的
subject = 'Some subject'
content = 'Some email content'
personalizations = []
for user, attachment_file in zip(users, attachment_files):
file_data = attachment_file.read()
file_name = os.path.basename(attachment_file.name)
encoded_file_data = base64.b64encode(file_data).decode('utf-8')
attachment = {
'content': encoded_file_data,
'filename': file_name,
'type': 'application/octet-stream',
'disposition': 'attachment'
}
personalization = {
'to': [{'email': user}],
'subject': subject,
'content': [
{'type': 'text/plain', 'value': content}
],
'attachments': [attachment]
}
data = {
'from': {'email': from_email},
'personalizations': personalizations
}
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
response = requests.post(
'https://api.sendgrid.com/v3/mail/send',
headers=headers,
data=json.dumps(data)
)
电子邮件大小和收件人数量有一些限制:https://docs.sendgrid.com/api-reference/mail-send/limitations