【问题标题】:Can't save new message to Drafts in gmail无法将新邮件保存到 gmail 中的草稿
【发布时间】:2018-04-14 05:51:46
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 你在使用 Python 3 吗?
  • @ElisByberi,是的

标签: python email gmail gmail-imap imaplib


【解决方案1】:

如果你使用的是 Python 库,这里是 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())}

一旦你创建了一个Message对象,你可以将它传递给drafts.create方法来创建一个Draft对象。

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

另外,这里有一个related SO post 声明:您已经解码字节对象以生成一个字符串。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-01
    • 2022-07-15
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    相关资源
    最近更新 更多