【发布时间】:2020-09-06 03:02:24
【问题描述】:
我正在将带有 API 的电子邮件插入我的邮箱。附件有效并且确实显示在电子邮件本身中。通常在收件箱/邮件列表视图中,右端有一个附件回形针符号,表示邮件有附件(https://i.imgur.com/XbYIE9b.png)。但这似乎不起作用。我生成电子邮件并插入它的代码如下。这是插入 API 的限制还是我没有正确生成带附件的电子邮件?
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from base64 import urlsafe_b64encode
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email import encoders
import mimetypes
import os
from apiclient import errors
from urllib.error import HTTPError
import time
import datetime
import re
import random
SCOPES = ['https://www.googleapis.com/auth/gmail.insert']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
message = MIMEMultipart('alternative')
part1 = MIMEText('just text', 'plain')
part2 = MIMEText('<b>html text<br><br>html text</b>', 'html')
message.attach(part1)
message.attach(part2)
filename = 'some.attachment'
part = MIMEApplication(open('/var/www/html/attachments/' + filename, 'rb').read())
part.add_header('Content-Disposition', f"attachment; filename=\"{filename}\"; size={os.path.getsize('/var/www/html/attachments/' + filename)}")
part.add_header('Content-Description', f"{filename}")
message.attach(part)
message['to'] = '"Some Body" <somebody@gmail.com>'
message['from'] = 'Some Other <from@email.com>'
message['subject'] = 'test email'
message['Content-Type'] = 'text/html; charset="utf-8"'
message['Content-Transfer-Encoding'] = 'base64'
encoded_message = urlsafe_b64encode(message.as_bytes())
temp = {'raw': encoded_message.decode(), 'labelIds': ['Some_Label', 'UNREAD']}
try:
message1 = service.users().messages().insert(userId='me', body=temp, internalDateSource='dateHeader').execute()
print(f"{message1['id']} / {message1['threadId']}/ {message1}")
except HTTPError as err:
print(err)
【问题讨论】:
-
查看this question 和resumable uploads 上的文档
-
@RafaGuillermo 根据您的链接修改代码here。它仍然会发送电子邮件,当我打开它时有一个附件,但没有在邮件列表中显示附件图像。