Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

google api - Sending an email with ruby gmail api v0.9

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: "[email protected]", 
from: "[email protected]", 
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 <[email protected]> - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...