Как сохранить черновик Gmail со встроенными изображениями? - PullRequest
0 голосов
/ 10 июля 2019

Я хочу использовать скрипт Python для сохранения черновика Gmail, содержащего встроенные изображения и отображаемый HTML-текст, чтобы его можно было проверить перед отправкой вручную.

Кажется, что протокол cid для прикрепления встроенных изображений доуне работает при отправке электронного письма, даже если черновик выглядит хорошо.

import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

import base64
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os
from apiclient import errors

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://mail.google.com/']

def CreateDraft(user_id, message_body):
    """Create and insert a draft email.

    Args:
        * service: Authorized Gmail API service instance.
        * user_id: User's email address. The special value "me"
          can be used to indicate the authenticated user.
        * message_body: The body of the email message, including headers.

    Returns:
        Draft object, including draft id and message meta data.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    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()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    try:
        message = {'message': message_body}
        draft = service.users().drafts().create(userId=user_id, body=message).execute()    
        return draft
    except errors.HttpError as error:
        print ('An error occurred: %s' % error)
        return None

def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir, filename):
    """Create a message for an email.

    Args:
      * sender: The email address of the sender.
      * to: The email address of the receiver.
      * subject: The subject of the email message.
      * message_text: The html text of the email message.
      * file_dir: The directory containing the file to be attached.
      * filename: The name of the file to be attached.

    Returns:
       An object containing a base64url encoded email object.
    """
    message = MIMEMultipart()
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    msg = MIMEText(message_text,'html')
    message.attach(msg)

    path = os.path.join(file_dir, filename)
    content_type, encoding = mimetypes.guess_type(path)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(path, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image': #The only useful one for images
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()

    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

Этот сценарий создает черновик с прикрепленным файлом.Однако, если файл является изображением, я бы хотел, чтобы он был встроенным, а не вложенным ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...