python - 如何使用 boto3 send_email 或 send_raw_email 发送 HTML 文本和附件?

标签 python python-2.7 boto3

如何使用 boto3 发送图像附件? SES send_email 客户端?

我知道我可以使用 send_raw_email 发送附件,但我需要发送带有 html 数据 的邮件正文。如果这不可能,我如何使用 boto3.ses.send_raw_email() 发送带有 html 数据的电子邮件?

最佳答案

在查阅了多个来源(包括其他 SO 问题、博客和 Python 文档)后,我得出了以下代码。

允许文本和/或 html 电子邮件和附件。

分离了 MIME 和 boto3 部分,以防您想将 MIME 重新用于其他目的,例如使用 SMTP 客户端而不是 boto3 发送电子邮件。

import os
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication


def create_multipart_message(
        sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None)\
        -> MIMEMultipart:
    """
    Creates a MIME multipart message object.
    Uses only the Python `email` standard library.
    Emails, both sender and recipients, can be just the email string or have the format 'The Name <the_email@host.com>'.

    :param sender: The sender.
    :param recipients: List of recipients. Needs to be a list, even if only one recipient.
    :param title: The title of the email.
    :param text: The text version of the email body (optional).
    :param html: The html version of the email body (optional).
    :param attachments: List of files to attach in the email.
    :return: A `MIMEMultipart` to be used to send the email.
    """
    multipart_content_subtype = 'alternative' if text and html else 'mixed'
    msg = MIMEMultipart(multipart_content_subtype)
    msg['Subject'] = title
    msg['From'] = sender
    msg['To'] = ', '.join(recipients)

    # Record the MIME types of both parts - text/plain and text/html.
    # According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred.
    if text:
        part = MIMEText(text, 'plain')
        msg.attach(part)
    if html:
        part = MIMEText(html, 'html')
        msg.attach(part)

    # Add attachments
    for attachment in attachments or []:
        with open(attachment, 'rb') as f:
            part = MIMEApplication(f.read())
            part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
            msg.attach(part)

    return msg


def send_mail(
        sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None) -> dict:
    """
    Send email to recipients. Sends one mail to all recipients.
    The sender needs to be a verified email in SES.
    """
    msg = create_multipart_message(sender, recipients, title, text, html, attachments)
    ses_client = boto3.client('ses')  # Use your settings here
    return ses_client.send_raw_email(
        Source=sender,
        Destinations=recipients,
        RawMessage={'Data': msg.as_string()}
    )


if __name__ == '__main__':
    sender_ = 'The Sender <the_sender@email.com>'
    recipients_ = ['Recipient One <recipient_1@email.com>', 'recipient_2@email.com']
    title_ = 'Email title here'
    text_ = 'The text version\nwith multiple lines.'
    body_ = """<html><head></head><body><h1>A header 1</h1><br>Some text."""
    attachments_ = ['/path/to/file1/filename1.txt', '/path/to/file2/filename2.txt']

    response_ = send_mail(sender_, recipients_, title_, text_, body_, attachments_)
    print(response_)

关于python - 如何使用 boto3 send_email 或 send_raw_email 发送 HTML 文本和附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998170/

相关文章:

python - 为什么我在使用 Twitter Rest API 时收到此错误

c++ - VS2008 中的简单 swig python 示例 - 导入错误 - 内部 (py)readline 错误

python-2.7 - SQLite3 : Using try: except: to establish db table & default data set - kosher?

python - 使用 boto3 对 dynamoDb 进行完整扫描

python - 将带有 unicode 字符的 XML 解析为 ElementTree

python - QLabel加载图片,调整大小

python 2.7 - 运行子进程并在用户时间超过最大时间时终止它

python - pip install boto3 出错

python-3.x - 如何从 python 向 AppSync 发送 GraphQL 查询?

python - 我可以直接在 s3 上上传图片而不保存在本地文件夹中吗?