使用Python和gmail API,如何发送带有多个附件的邮件?

时间:2019-03-20 22:25:51

标签: python python-3.x rest gmail-api

试图创建和发送带有多个文件的邮件。 Per the online gmail api documentation,具有构建带有附件的邮件的功能,但是没有文档说明如何使用它来创建具有多个附件的邮件。

我可以使用gmail API以编程方式发送带有多个附件的邮件吗?怎么可能呢?

1 个答案:

答案 0 :(得分:1)

使用此功能,您可以发送给一个或多个收件人电子邮件,还可以附加零个,一个或多个文件。欢迎提出编码改进建议,但是现在就可以了。

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)上激活安全性较低的应用,以使此代码正常工作。

希望这会有所帮助