SendGridAPIClient():Python中发送带有附件的电子邮件的示例代码
发布时间:2023-12-15 09:50:40
SendGridAPIClient()是一个Python库,用于发送电子邮件,包括带有附件的邮件。通过使用SendGrid的API,我们可以轻松地发送带有附件的邮件。
以下是SendGridAPIClient()的示例代码:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition
def send_email_with_attachment(to_email, subject, body, attachment_path):
message = Mail(
from_email='YOUR_EMAIL@EXAMPLE.COM',
to_emails=to_email,
subject=subject,
plain_text_content=body)
with open(attachment_path, 'rb') as f:
data = f.read()
f.close()
attachment = Attachment()
attachment.file_content = FileContent(data)
attachment.file_name = FileName(os.path.basename(attachment_path))
attachment.file_type = FileType("application/pdf")
attachment.disposition = Disposition("attachment")
message.attachment = attachment
try:
sg = SendGridAPIClient('SENDGRID_API_KEY')
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(str(e))
# Example usage
send_email_with_attachment('recipient@example.com', 'Test Email', 'This is a test email with attachment.', 'path/to/attachment.pdf')
在上面的代码中,我们首先导入了必要的模块。然后,我们定义了一个名为send_email_with_attachment()的函数,该函数接受收件人邮箱、邮件主题、邮件正文以及附件路径作为参数。
在函数内部,我们使用SendGrid的API密钥来实例化一个SendGridAPIClient对象。然后,我们创建了一个Mail对象,设置了发件人、收件人、主题和正文。
接下来,我们打开附件文件,并将其内容读取为二进制数据。然后,我们创建一个Attachment对象,并将附件的内容、文件名、文件类型和处置(attachment)设置为该对象的属性。
最后,我们将attachment对象赋值给邮件对象的attachment属性。然后,我们使用SendGridAPIClient的send()方法来发送邮件。发送后,我们打印出响应的状态码、正文和头部信息。
在示例的最后,我们调用send_email_with_attachment()函数,并传递示例参数来发送带有附件的电子邮件。
请注意,您需要将'YOUR_EMAIL@EXAMPLE.COM'替换为您的有效电子邮件地址,并将'SENDGRID_API_KEY'替换为您的SendGrid API密钥。
希望这个示例代码对您有所帮助!
