如何向多个收件人发送邮件?

时间:2014-08-22 00:11:18

标签: python mime gmail-api rfc2822

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

  

发生错误:   https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json   返回“标题无效”>

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

该指南指出Gmail API需要符合RFC-2822的邮件。我再次使用RFC-2822指南中的一些寻址示例没有太多运气: https://tools.ietf.org/html/rfc2822#appendix-A

我的印象是'mary @ x.test,jdoe @ example.org,one @ y.test'应该是一个有效的字符串,可以传递到CreateMessage的'to'参数,但是我从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)

3 个答案:

答案 0 :(得分:2)

获取&#34;标题无效&#34;当在单个标题中发送多个收件人(逗号分隔)时,回归率已在2014-08-25修复。

答案 1 :(得分:1)

正如詹姆斯在评论中所说,当Python对使用SMTP提供出色的文档支持时,您不应该浪费时间尝试使用Gmail API:email模块可以撰写包含附件的邮件,并smtplib发送他们。恕我直言,您可以将Gmail API用于开箱即用的,但在出现问题时应使用Python标准库中的强大模块。

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

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

答案 2 :(得分:0)

另见User.drafts reference - error"Invalid to header"

显然,最近在Gmail API中引入了此错误。

相关问题