python - 使用 Python 和 gmail API,我如何发送带有多个附件的消息?
问题描述
希望创建和发送带有多个附加文件的消息。根据在线 gmail api 文档,有一个用于构建带有附件的消息的功能,但没有关于如何使用它来创建带有多个附件的消息的文档。
我可以使用 gmail 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 ) 上激活安全性较低的应用程序,以使此代码正常工作。
希望这可以帮助
推荐阅读
- python - sympy TypeError:无法确定关系的真值
- python - 使用 jit 在 Python 中执行 N 维嵌套循环
- oracle - 防止 Oracle 上事务的并发错误
- python - Django 模板:如果 .. 在
- php - 条件语句在 PHP 7.4 中没有给出所需的输出
- apache - Apache 文件夹和文件何时返回 404 Not Found 应该在 Linux 上返回 403 Forbidden
- sql - 您如何为一个键存储多行数据并保持良好的规范化实践?
- php - 点击提交按钮后会出现一个白页
- docker - 无法使用 IP 地址访问本地 docker 容器
- r - R提取字符串中的特定文本