12

我在使用 Gmail API 向多个地址发送邮件时遇到了一些问题。我只成功地向一个地址发送了一条消息,但是当我在'To'字段中包含多个以逗号分隔的地址时出现以下错误:

发生错误:<HttpError 400 when requesting
https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json 返回“Invalid to header”>

我正在使用此 Gmail API 指南 中的CreateMessage和方法: https ://developers.google.com/gmail/api/guides/sendingSendMessage

该指南指出,Gmail API 要求邮件符合 RFC-2822。在 RFC-2822 指南中使用其中一些寻址示例,我再次运气不佳: https ://www.rfc-editor.org/rfc/rfc2822#appendix-A

我的印象是 'mary@x.test, jdoe@example.org, one@y.test' 应该是传递给 'to' 参数的有效字符串CreateMessage,但我收到的错误SendMessage引导我否则相信。

请让我知道您是否可以重新创建此问题,或者您对我可能在哪里犯错有任何建议。谢谢!

编辑:这是产生错误的实际代码......

def CreateMessage(sender, to, subject, message_text):
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def SendMessage(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message)
           .execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error

def ComposeEmail():
    # build gmail_service object using oauth credentials...
    to_addr = 'Mary Smith <mary@x.test>, jdoe@example.org, Who? <60one@y.test>'
    from_addr = 'me@address.com'
    message = CreateMessage(from_addr,to_addr,'subject text','message body')
    message = SendMessage(gmail_service,'me',message)
4

3 回答 3

2

在单个标头中与多个收件人(逗号分隔)一起发送时出现“标头无效”是 2014 年 8 月 25 日修复的回归。

于 2014-08-23T23:38:21.207 回答
1

正如 James 在其评论中所说,当 Python 对使用 SMTP 具有出色的文档支持时,您不应该浪费时间尝试使用 Gmail API:email模块可以编写包含附件的消息并smtplib发送它们。恕我直言,您可以将 Gmail API 用于开箱即用的功能,但在出现问题时应使用 Python 标准库中的健壮模块。

看起来您想发送纯文本消息:这是一个改编自email模块文档和How to send email in Python via SMTPLIB from Mkyong.com 的解决方案:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

msg = MIMEText('message body')
msg['Subject'] = 'subject text'
msg['From'] = 'me@address.com'
msg['To'] = 'Mary Smith <mary@x.test>, jdoe@example.org, "Who?" <60one@y.test>'

# Send the message via Gmail SMTP server.
gmail_user = 'youruser@gmail.com'
gmail_pwd = 'yourpassword'smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver = smtplib.SMTP('smtp.gmail.com')smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
smtpserver.send_message(msg)
smtpserver.quit()
于 2014-08-24T09:07:58.870 回答
0

另请参阅User.drafts 参考 - 错误“对标头无效”

显然这个错误是最近在 Gmail API 中引入的。

于 2014-08-22T17:37:39.323 回答