[ rails ] ActiveMailer send email to Gmail using SMTP and TLS

Mailer

app/mailers/user_mailer.rb

class UserMailer < ApplicationMailer
helper :application

def generate(recipients:, params2:)
attachments["#{Date.yesterday}.csv"] = "x,y,z"
mail(
to: recipients,
subject: "#{name}--#{Date.today}",
body: 'Report is attached'
)
end

end

 

Send email

UserMailer.generate(
param1: 'whatever',
param2: 'whatever'
).deliver_now!

NOTE*** : the ! after deliver_now will force rails to throw error.

 

SMTP setting

config/environment.rb

ActionMailer::Base.smtp_settings = {
user_name: 'phong.ek@gmail.com',
password: 'whatever',
domain: 'gmail.com',
address: 'smtp.gmail.com',
port: 587,
authentication: :plain,
enable_starttls_auto: true
}

 

Common error and solution

Error#1

EOFError: end of file reached
from /home/pong/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/protocol.rb:153:in `read_nonblock'

Root cause#1

One of the root cause is using SSL port 465 with TLS.

NOTE : According to https://support.google.com/a/answer/176600?hl=en, port 587 must be TLS, port 465 should be SSL.

 

Error#2

Username and Password are not accepted

Root cause#2

See https://dsin.wordpress.com/2017/09/28/gmail-unable-to-send-email/

 

Useful params in config/development.rb

The above script log the error even the environment configuration is below.

config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_deliveries = false

 

Mail Catcher
Another interesting rails mail server is https://mailcatcher.me/.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s