12

Gmail API を使用して複数のアドレスにメッセージを送信するのに問題があります。1 つのアドレスにのみメッセージを送信できましたが、'To'フィールドにカンマ区切りの複数のアドレスを含めると、次のエラーが発生します。

エラーが発生しました: <HttpError 400 when requesting
https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "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

1

James がコメントで述べているように、Python が SMTP を使用するための文書化された優れたサポートを提供している場合、Gmail API を使用しようとして時間を無駄にすべきではありません。emailモジュールは、添付ファイルを含むメッセージを作成してsmtplib送信できます。私見では、Gmail API をすぐに使用できますが、問題が発生した場合は Python 標準ライブラリからの堅牢なモジュールを使用する必要があります。

テキストのみのメッセージを送信したいようです: これは、emailモジュールのドキュメントと、Mkyong.com から SMTPLIB を介して Python で電子メールを送信する方法を基にしたソリューションです:

# 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 に答える