0

I am trying to create and save message to Drafts in gmail, but nothing happen.

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()

When I am changing msg.as_bytes() to msg.as_string(), I got the error below:

TypeError: cannot use a bytes pattern on a string-like object
MαπμQμαπkγVπ.0
  • 5,887
  • 1
  • 27
  • 65
Dmitrii K
  • 249
  • 2
  • 13

1 Answers1

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.

Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91