Search code examples
rubygmailgmail-apigoogle-api-ruby-client

Unable to send Gmail Message with Gmail API


Using the Gmail Service to send an email, but I'm having problem with the email format which needs to be passed to Google::Apis::GmailV1::Message, I'm passing raw parameter to it in the following format

email_raw = "From: <#{@google_account}>
To: <#{send_to}>
Subject: This is the email subject

The email body text goes here"

# raw is: The entire email message in an RFC 2822 formatted and base64url encoded string.

message_to_send = Google::Apis::GmailV1::Message.new(raw: Base64.encode64(email_raw))
response = @service.send_user_message("me", message_to_send)

This fails even when I pass email_raw without base64 encoding. I'm providing valid emails but it fails with an error

Google::Apis::ClientError (invalidArgument: Recipient address required)

I've checked Sending an email with ruby gmail api v0.9 and I also found this but it uses Mail class which I could not locate in the Gmail API Ruby client library. Currently, email_raw contains \n characters but I've tested it without it and it doesn't work.
Moreover, I also want to send attachments in a message.


Solution

  • We can easily offload the effort of forming a standardized and formatted email to this gem. Just include the gem in your project and do this

    mail = Mail.new
    mail.subject = "This is the subject"
    mail.to = "[email protected]"
    # to add your html and plain text content, do this
    mail.part content_type: 'multipart/alternative' do |part|
      part.html_part = Mail::Part.new(body: email_body, content_type: 'text/html')
      part.text_part = Mail::Part.new(body: email_body)
    end
    # to add an attachment, do this
    mail.add_file(params["file"].tempfile.path)
    
    # when you do mail.to_s it forms a raw email text string which you can supply to the raw argument of Message object
    message_to_send = Google::Apis::GmailV1::Message.new(raw: mail.to_s)
    # @service is an instance of Google::Apis::GmailV1::GmailService
    response = @service.send_user_message("me", message_to_send)