首页 > 解决方案 > 使用 Python 和 gmail API,我如何发送带有多个附件的消息?

问题描述

希望创建和发送带有多个附加文件的消息。根据在线 gmail api 文档,有一个用于构建带有附件的消息的功能,但没有关于如何使用它来创建带有多个附件的消息的文档。

我可以使用 gmail API 以编程方式发送带有多个附件的消息吗?怎么可能做到这一点?

标签: pythonpython-3.xrestgmail-api

解决方案


使用此功能,您可以向一个或多个收件人发送电子邮件,也可以附加零个、一个或多个文件。欢迎提出编码改进建议,但它现在的方式是有效的。

Python v3.7

来自https://github.com/python/cpython/blob/3.7/Lib/smtplib.py的smtplib (下载代码并在您的项目文件夹中创建 smtplib.py)

def send_email(se_from, se_pwd, se_to, se_subject, se_plain_text='', se_html_text='', se_attachments=[]):
    """ Send an email with the specifications in parameters

    The following youtube channel helped me a lot to build this function:
    https://www.youtube.com/watch?v=JRCJ6RtE3xU
    How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
    Corey Schafer youtube channel

    Input:
        se_from : email address that will send the email
        se_pwd : password for authentication (uses SMTP.SSL for authentication)
        se_to : destination email. For various emails, use ['email1@example.com', 'email2@example.com']
        se_subject : email subject line
        se_plain_text : body text in plain format, in case html is not supported
        se_html_text : body text in html format
        se_attachments : list of attachments. For various attachments, use ['path1\file1.ext1', 'path2\file2.ext2', 'path3\file3.ext3']. Follow your OS guidelines for directory paths. Empty list ([]) if no attachments

    Returns
    -------
        se_error_code : returns True if email was successful (still need to incorporate exception handling routines)
    """

    import smtplib
    from email.message import EmailMessage

    # Join email parts following smtp structure
    msg = EmailMessage()
    msg['From'] = se_from
    msg['To'] = se_to
    msg['Subject'] = se_subject
    msg.set_content(se_plain_text)
    # Adds the html text only if there is one
    if se_html_text != '':
        msg.add_alternative("""{}""".format(se_html_text), subtype='html')

    # Checks if there are files to be sent in the email
    if len(se_attachments) > 0:
        # Goes through every file in files list
        for file in se_attachments:
            with open(file, 'rb') as f:
                file_data = f.read()
                file_name = f.name
            # Attaches the file to the message. Leaves google to detect the application to open it
            msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    # Sends the email that has been built
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(se_from, se_pwd)
        smtp.send_message(msg)

    return True

不要忘记在您的 google 帐户 ( https://myaccount.google.com/lesssecureapps ) 上激活安全性较低的应用程序,以使此代码正常工作。

希望这可以帮助


推荐阅读