无法将新邮件保存到Gmail中的草稿

时间:2017-11-01 20:09:19

标签: python email gmail gmail-imap imaplib

我正在尝试在gmail中创建并保存消息给草稿,但没有任何反应。

import time
import random
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import imaplib

def save_draft(email_to, body, login, password, image):
    msg = MIMEMultipart("alternative")
    msg.set_charset("utf-8")
    msg.attach(MIMEText(body, "plain", "utf-8"))
    msg['Subject'] = SUBJECT
    msg['From'] = login
    msg['To'] = email_to
    with open(image, 'rb') as f:
        part = MIMEApplication(
            f.read(),
            Name=image
        )
    part['Content-Disposition'] = 'attachment; filename={}'.format(IMAGE)
    msg.attach(part)

    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login(login, password)
    imap.select('[Gmail]/Drafts')

    now = imaplib.Time2Internaldate(time.time())
    imap.append('[Gmail]/Drafts',
                '',
                now,
                msg.as_bytes())
    imap.logout()

当我将msg.as_bytes()更改为msg.as_string()时,我收到以下错误:

TypeError: cannot use a bytes pattern on a string-like object

1 个答案:

答案 0 :(得分:0)

If you are using Python library here is the code snippet:

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

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

  Returns:
    An object containing a base64url encoded email object.
  """
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string())}

Once you have created a Message object, you can pass it to the drafts.create method to create a Draft object.

def create_draft(service, user_id, message_body):
  """Create and insert a draft email. Print the returned draft's message and id.

  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.
  """
  try:
    message = {'message': message_body}
    draft = service.users().drafts().create(userId=user_id, body=message).execute()

    print 'Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])

    return draft
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

Also, here is a related SO post that stated: you have decode the bytes object to produce a string.

Hope this helps.