ben
ben

Reputation: 6180

Sending HTML email using gmail API in ruby

I am creating a ruby script and it should do the above. Over the day I was trying to crack I way to send an HTML email to a selected number of emails addresses. There is no clear documentation on how I should do, So please I will appreciate you helping.

Here is my code, The script is successfully authorizing a user and picking the code to access his/her gmail account. Now I want to send the HTML email on behalf of that user.

require 'rubygems'
require 'google/api_client'
require 'launchy'

CLIENT_ID = 'my_app_Id_on_gmail_developers_console'
CLIENT_SECRET = 'the_secret_key'
OAUTH_SCOPE = 'https://mail.google.com/'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Create a new API client & load the Google Drive API
client = Google::APIClient.new(:application_name => 'Ruby Gmail sample',
                               :application_version => '1.0.0')
gmail = client.discovered_api('gmail', "v1")

# Request authorization
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.scope = OAUTH_SCOPE
client.authorization.redirect_uri = REDIRECT_URI

uri = client.authorization.authorization_uri
Launchy.open(uri)

# Exchange authorization code for access token
$stdout.write  "Enter authorization code: "
client.authorization.code = gets.chomp
client.authorization.fetch_access_token!

#testing if it is working well by counting the emails.
@emails = client.execute(
    api_method: gmail.users.messages.list,
    parameters: {
        userId: "me"},
    headers: {'Content-Type' => 'application/json'}
)

count = @emails.data.messages.count
puts "you have #{count} emails "
# Pretty print the API result
jj @emails.data.messages

how can I do this? is there a way I can an external html file which is the email file to be sent. then I can sent this file using the script?

Upvotes: 1

Views: 1530

Answers (2)

Michal Macejko
Michal Macejko

Reputation: 370

I partially accept the answer above since you can send an email through STMP pretty easily but with the gmail API it's even easier. According your code it should looks like this:

message              = Mail.new
message.date         = Time.now
message.subject      = 'Supertramp'
message.body         = "<p>Hi Alex, how's life?</p>"
message.content_type = 'text/html'
message.from         = "Michal Macejko <[email protected]>"
message.to           = '[email protected]'

service = client.discovered_api('gmail', 'v1')

result = client.execute(
  api_method: service.users.messages.to_h['gmail.users.messages.send'],
  body_object: {
    raw: Base64.urlsafe_encode64(message.to_s)
  },
  parameters:  {
    userId: '[email protected]'
  },
    headers:   { 'Content-Type' => 'application/json' }
)

response = JSON.parse(result.body)

For multi-part email with the attachment:

message         = Mail.new
message.date    = Time.now
message.subject = 'Supertramp'
message.from    = "Michal Macejko <[email protected]>"
message.to      = '[email protected]'

message.part content_type: 'multipart/alternative' do |part|
  part.html_part = Mail::Part.new(body: "<p>Hi Alex, how's life?</p>", content_type: 'text/html; charset=UTF-8')
  part.text_part = Mail::Part.new(body: "Hi Alex, how's life?")
end

open('http://google.com/image.jpg') do |file| 
  message.attachments['image.jpg'] = file.read 
end

Upvotes: 6

Schylar
Schylar

Reputation: 774

Just my input. I was able to create a script that emailed html to multiple users in about 100 lines. Without using an api. You need to look into using smtp. It is very simple. You define a server for it to use and then you use it's "send_message" method. Here's a link to a good site! GOOD SITE

I can't post my whole code here for security reasons however this should get you started

class Email_Client

attr_accessor :message_contents, :subject

  def initialize(sender_name, receiver_name, sender_email, receiver_email)
    @sender_name = sender_name
    @receiver_name = receiver_name
    @sender_email = sender_email
    @receiver_email = receiver_email
  end

    def send_html

message = <<MESSAGE
From: #{@sender_name} <#{@sender_email}>
To: #{@receiver_name} <#{@receiver_email}>
MIME-Version: 1.0
Content-type: text/html
Subject: #{subject}

#{message_contents}

MESSAGE

      Net::SMTP.start('SeRvEr_HeRe') do |smtp|
      smtp.send_message message,
      @sender_email, 
      @receiver_email
      end

end

Upvotes: 2

Related Questions