Sending an email with ruby gmail api v0.9

2019-06-26 23:36发布

问题:

Does anyone have a simple example as to how to send an email from scratch with the v0.9 API.

simply want an example of sending the following:

m = Mail.new(
to: "test1@test.com", 
from: "test2@test.com", 
subject: "Test Subject",
body:"Test Body")

Now to create that message object which is required to send,we can use:

msg = Base64.urlsafe_encode64 m.to_s

And then try to send (where message_object = msg):

client = Google::Apis::GmailV1::GmailService.new #Appropriately authorised
client.send_user_message("me", message_object)

The client wants an RFC822 compatible encoded string, which the above should be.

I've tried:

message_object = msg
=> Google::Apis::ClientError: invalidArgument: 'raw' RFC822 payload message string or uploading message via /upload/* URL required
message_object = raw:msg
=>ArgumentError: unknown keyword: raw
message_object = {raw:msg}
=>ArgumentError: unknown keyword: raw 
message_object = Google::Apis::GmailV1::Message.new(raw:msg)
=> #<Google::Apis::GmailV1::Message:0x007f9158e5b4b0 @id="15800cd7178d69a4", @thread_id="15800cd7178d69a4">
#But then I get Bounce <nobody@gmail.com> - An error occurred. Your message was not sent.

i.e. None of them work...

Sending the basic encded string (msg above) through the Gmail API interface tester here works.

I'm obviously missing something obvious here as to how to construct that object required to make it work through the API.

回答1:

Ok. So the answer... thanks for all your help Holger... Was that the documentation is wrong. It asks you to encode to base64. The base64 encoding is not required (it is done internally by the api client).

The correct way to send is

msg = m.encoded 
# or m.to_s
# this doesn't base64 encode. It just turns the Mail::Message object into an appropriate string.

message_object = Google::Apis::GmailV1::Message.new(raw:m.to_s)
client.send_user_message("me", message_object)

Hope that saves someone else from being patronised by an overzealous mod.



回答2:

Carpela‘s answer works fine, but for the message_object, it's missing "raw" in Message.new. The correct code should as following:

message_object = Google::Apis::GmailV1::Message.new(raw: m.encoded) # or m.to_s
client.send_user_message('me', message_object)