- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试发送一封电子邮件,其中的附件(最好是多个附件)大于 10 MB 且小于总大小限制 25 MB。我提到 10 MB 的原因是因为它似乎是当附加文件的正常方式停止工作并且您收到 错误 10053
时的下限。
我在文档中读到,执行此操作的最佳方法是使用 resumable upload方法,但我无法让它工作,也无法在 Python 中找到任何好的示例。大多数关于此的 SO 问题只是链接回没有 Python 示例的文档,或者他们的代码导致其他错误。
我正在寻找 Python 的解释,因为我想确保我理解正确。
我看过的问题:
代码:
import base64
import json
import os
from email import utils, encoders
from email.message import EmailMessage
from email.mime import application, multipart, text, base, image, audio
import mimetypes
from apiclient import errors
from googleapiclient import discovery, http
from google.oauth2 import service_account
def send_email(email_subject, email_body, email_sender='my_service_account@gmail.com', email_to='', email_cc='', email_bcc='', files=None):
# Getting credentials
with open(os.environ.get('SERVICE_KEY_PASSWORD')) as f:
service_account_info = json.loads(f.read())
# Define which scopes we're trying to access
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
# Setting up credentials using the gmail api
credentials = service_account.Credentials.from_service_account_info(service_account_info, scopes=SCOPES)
# This allows us to assign an alias account to the message so that the messages aren't coming from 'ServiceDriod-8328balh blah blah'
delegated_credentials = credentials.with_subject(email_sender)
# 'Building' the service instance using the credentials we've passed
service = discovery.build(serviceName='gmail', version='v1', credentials=delegated_credentials)
# Building out the email
message = multipart.MIMEMultipart()
message['to'] = email_to
message['from'] = email_sender
message['date'] = utils.formatdate(localtime=True)
message['subject'] = email_subject
message['cc'] = email_cc
message['bcc'] = email_bcc
message.attach(text.MIMEText(email_body, 'html'))
for f in files or []:
mimetype, encoding = mimetypes.guess_type(f)
# If the extension is not recognized it will return: (None, None)
# If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
# For an unrecognized extension we set mimetype to 'application/octet-stream' so it won't return None again.
if mimetype is None or encoding is not None:
mimetype = 'application/octet-stream'
main_type, sub_type = mimetype.split('/', 1)
# Creating the attachement:
# This part is used to tell how the file should be read and stored (r, or rb, etc.)
if main_type == 'text':
print('text')
with open(f, 'rb') as outfile:
attachement = text.MIMEText(outfile.read(), _subtype=sub_type)
elif main_type == 'image':
print('image')
with open(f, 'rb') as outfile:
attachement = image.MIMEImage(outfile.read(), _subtype=sub_type)
elif main_type == 'audio':
print('audio')
with open(f, 'rb') as outfile:
attachement = audio.MIMEAudio(outfile.read(), _subtype=sub_type)
elif main_type == 'application' and sub_type == 'pdf':
with open(f, 'rb') as outfile:
attachement = application.MIMEApplication(outfile.read(), _subtype=sub_type)
else:
attachement = base.MIMEBase(main_type, sub_type)
with open(f, 'rb') as outfile:
attachement.set_payload(outfile.read())
encoders.encode_base64(attachement)
attachement.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f))
message.attach(attachement)
media_body = http.MediaFileUpload(files[0], chunksize=500, resumable=True)
print('Uploading large file...')
body = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
message = (service.users().messages().send(userId='me', body=body, media_body=media_body).execute())
注意:现在,在 MediaFileUpload 中,我正在使用 files[0]
,因为我只使用一个文件进行测试,我只想附加一个暂时归档,直到它起作用。
错误:
Exception has occurred: ResumableUploadError
<HttpError 400 "Bad Request">
File "C:\Users\CON01599\AppData\Local\Continuum\anaconda3\Lib\site-packages\googleapiclient\http.py", line 927, in next_chunk
raise ResumableUploadError(resp, content)
File "C:\Users\CON01599\AppData\Local\Continuum\anaconda3\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\CON01599\AppData\Local\Continuum\anaconda3\Lib\site-packages\googleapiclient\http.py", line 822, in execute
_, body = self.next_chunk(http=http, num_retries=num_retries)
File "C:\Users\CON01599\AppData\Local\Continuum\anaconda3\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\CON01599\Documents\GitHub\pipelines\components\email\send_email.py", line 105, in send_email
message = (service.users().messages().send(userId='me', body=body, media_body=media_body).execute())
回答:
import base64
import io
import json
import os
from email import utils, encoders
from email.message import EmailMessage
from email.mime import application, multipart, text, base, image, audio
import mimetypes
from apiclient import errors
from googleapiclient import discovery, http
from google.oauth2 import service_account
def get_environment_variables():
""" Retrieves the environment variables and returns them in
a dictionary object.
"""
env_var_dict = {
'to': os.environ.get('TO'),
'subject': os.environ.get('SUBJECT'),
'body': os.environ.get('BODY'),
'file': os.environ.get('FILE')
}
return env_var_dict
def send_email(email_subject, email_body, email_sender='my_service_account@gmail.com', email_to='', email_cc='', email_bcc='', files=None):
# Pulling in the string value of the service key from the parameter
with open(os.environ.get('SERVICE_KEY_PASSWORD')) as f:
service_account_info = json.loads(f.read())
# Define which scopes we're trying to access
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
# Setting up credentials using the gmail api
credentials = service_account.Credentials.from_service_account_info(service_account_info, scopes=SCOPES)
# This allows us to assign an alias account to the message so that the messages aren't coming from 'ServiceDriod-8328balh blah blah'
delegated_credentials = credentials.with_subject(email_sender)
# 'Building' the service instance using the credentials we've passed
service = discovery.build(serviceName='gmail', version='v1', credentials=delegated_credentials)
# Building out the email
message = multipart.MIMEMultipart()
message['to'] = email_to
message['from'] = email_sender
message['date'] = utils.formatdate(localtime=True)
message['subject'] = email_subject
message['cc'] = email_cc
message['bcc'] = email_bcc
message.attach(text.MIMEText(email_body, 'html'))
for f in files or []:
f = f.strip(' ')
mimetype, encoding = mimetypes.guess_type(f)
# If the extension is not recognized it will return: (None, None)
# If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
# For an unrecognized extension we set mimetype to 'application/octet-stream' so it won't return None again.
if mimetype is None or encoding is not None:
mimetype = 'application/octet-stream'
main_type, sub_type = mimetype.split('/', 1)
# Creating the attachement:
# This part is used to tell how the file should be read and stored (r, or rb, etc.)
if main_type == 'text':
print('text')
with open(f, 'rb') as outfile:
attachement = text.MIMEText(outfile.read(), _subtype=sub_type)
elif main_type == 'image':
print('image')
with open(f, 'rb') as outfile:
attachement = image.MIMEImage(outfile.read(), _subtype=sub_type)
elif main_type == 'audio':
print('audio')
with open(f, 'rb') as outfile:
attachement = audio.MIMEAudio(outfile.read(), _subtype=sub_type)
elif main_type == 'application' and sub_type == 'pdf':
with open(f, 'rb') as outfile:
attachement = application.MIMEApplication(outfile.read(), _subtype=sub_type)
else:
attachement = base.MIMEBase(main_type, sub_type)
with open(f, 'rb') as outfile:
attachement.set_payload(outfile.read())
encoders.encode_base64(attachement)
attachement.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f))
message.attach(attachement)
media_body = http.MediaIoBaseUpload(io.BytesIO(message.as_bytes()), mimetype='message/rfc822', resumable=True)
body_metadata = {} # no thread, no labels in this example
try:
print('Uploading file...')
response = service.users().messages().send(userId='me', body=body_metadata, media_body=media_body).execute()
print(response)
except errors.HttpError as error:
print('An error occurred when sending the email:\n{}'.format(error))
if __name__ == '__main__':
env_var_dict = get_environment_variables()
print("Sending email...")
send_email(email_subject=env_var_dict['subject'],
email_body=env_var_dict['body'],
email_to=env_var_dict['to'],
files=env_var_dict['file'].split(','))
print("Email sent!")
最佳答案
您在这里遇到的问题是您的 MediaUpload
是单个附件。
您需要将整个 RFC822 消息作为可恢复的 MediaUpload
上传,而不是将单个附件作为可恢复的 MediaUpload
上传。 p>
换句话说:
import ...
...
from io import BytesIO
from googleapiclient.http import MediaIoBaseUpload
SCOPES = [ 'scopes' ]
creds = get_credentials_somehow()
gmail = get_authed_service_somehow()
msg = create_rfc822_message(headers, email_body)
to_attach = get_attachment_paths_from_dir('../reports/tps/memos/2019/04')
add_attachments(msg, to_attach)
media = MediaIoBaseUpload(BytesIO(msg.as_bytes()), mimetype='message/rfc822', resumable=True)
body_metadata = {} # no thread, no labels in this example
resp = gmail.users().messages().send(userId='me', body=body_metadata, media_body=media).execute()
print(resp)
# { "id": "some new id", "threadId": "some new thread id", "labelIds": ["SENT"]}
我根据您提供的代码将其拼凑在一起,审查了 this GitHub issue和 Google 的收件箱到 Gmail 电子邮件导入器,特别是 this bit .
当发送对现有邮件的回复时,您几乎肯定会有某种元数据,您应该提供这些元数据以帮助 Gmail 跟踪您的新回复和原始对话。即,您将传递信息性元数据,而不是空的 body
参数,例如
body_metadata = { 'labelIds': [
"your label id here",
"another label id" ],
'threadId': "some thread id you took from the message you're replying to"
}
其他好的引用:
关于python - 如何使用 Python - Gmail API 将大文件附加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55542231/
我关注了 tutorial on creating a popup for an add-on在 Firefox 中,效果很好。 我现在遇到的问题是它创建的弹出窗口不会更改大小以适应我添加到其中的内容
我有一些视频,我需要连接一个标题并添加一些覆盖,问题是我需要先做覆盖,否则时间不正确,然后才将标题连接到视频的开头 ffmpeg -i talk.mp4 -i start_pancarte.png
我正在尝试附加一个 CSV 文件。这是我正在使用的线路。不幸的是,我找不到 export-csv 的附加选项。任何想法都有助于使其发挥作用。 Get-ADGroupMember "Domain Adm
我正在努力理解 Attach API (com.sun.tools.attach.*) 的用途。它的典型用途是什么?它是为了“模拟”JVM,以便您可以在不部署/启动代码的情况下测试您的代码吗?它是一个
我不明白为什么这不起作用。 soup_main = BeautifulSoup('FooBar') soup_append = BeautifulSoup('Meh') soup_main.body.
我有以下代码来返回我想要的字符串 $sql = " SELECT `description` FROM `auctions` WHERE `description` REGEX
我正在尝试从数组中附加具有多个值的元素,但我做错了。这是我的代码: for(var i=0; i ` + pricesArray[i].start_date ` ` + pricesArray[i
我正在尝试将图像链接添加到此 javascript 附加表中。使图像位于按钮上方 这是代码 $("#1").append(""+section+""+no+""+price+""+button+""
我有一个问题,我已经解决了,但它太烦人了。 我有一个 js 代码,当使用“追加”按下按钮时,它会放下一些 html 代码,并且通过该代码,我为 x 按钮提供了一个 id,并为容器元素提供了一个 id。
我想逐行读取文件,并且每一行可能都有很多字符。 这个版本的readline效果很好 func readLine(r *bufio.Reader) ([]byte, error) { var (
我有一个网站,每次用户登录或注销时,我都会将其保存到文本文件中。 如果不存在,我的代码在附加数据或创建文本文件时不起作用。这是示例代码 $myfile = fopen("logs.txt", "wr"
我正在尝试使用 typescript 和 Formik 创建一个自定义输入字段。我可以就完成以下代码的最佳方式获得一些帮助吗?我需要添加额外的 Prop 标签和名称......我已经坚持了一段时间,希
我有一个字符串 big_html,我想将它添加到某个 div 中。我观察到以下方面的性能差异: $('#some-div').append( big_html ); // takes about 10
如何使用 FormData 创建以下结果 ------WebKitFormBoundaryOmz20xyMCkE27rN7 Content-Disposition: form-data; name="
有没有办法附加 jQuery 事件处理程序,以便在任何先前附加的事件处理程序之前触发该处理程序?我遇到了this article ,但代码不起作用,因为事件处理程序不再存储在数组中,而这正是他的代码所
我正在开发一个需要网络登录的 iPhone 应用程序。像往常一样我打电话 [[UIApplication sharedApplication] openURL:loginURL]; 这将关闭应用程序并
我想开发一个仅针对特定域激活的扩展。 我不希望它在不浏览此特定域时出现在浏览器菜单中。 有可能这样做吗? 最佳答案 可能:对于菜单,您可以添加一个弹出窗口侦听器,用于检查当前加载的URL(docs f
这段 JavaScript 代码 function writeCookie(CookieName, CookieValue, CookieDuration) { var expiration
我正在使用 Handlebars 来渲染使用ajax从本地服务器获得的信息。我的 HTML 看起来像: {{#each Tabs}}
我尝试了以下代码,但当输入框中没有数据时它不会通知。当我直接添加此内容(不附加)时,它会起作用。我在这里做错了什么 var output = "\n"+ "\n"+
我是一名优秀的程序员,十分优秀!