Sendgrid set up on Rails 4 - ruby-on-rails

I have a rails 4 app. I set up ActionMailer and I can send order confirmation emails via localhost and gmail.
I installed Sendgrid on Heroku and followed the set up instructions. I get a Net::SMTPSyntaxError (501 Syntax error
my environment.rb (i have sendgrid user/pwd in application.yml)
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
in production.rb - the only actionamailer setting i have is this. I have this as a placeholder to put the real domain in later. I'm currently using herokuapp.com.
config.action_mailer.default_url_options = { host: 'localhost:3000' }
in my orders_controller within the order create method, I call the below.
AutoNotifier.orderconf_email(current_user, #order).deliver
auto_notifier.rb
class AutoNotifier < ActionMailer::Base
default from: "Test Email"
def orderconf_email(current_user, order)
#buyer = current_user
#order = order
mail(to: #buyer.email, subject: 'Thank you for your order.')
end
end
What am I missing? It works on localhost with gmail so I'm missing something in the sendgrid settings or in the default_url in production.rb file.

For posterity, here's a working setup for external SMTP in Rails on Heroku:
#config/environments/production.rb
config.action_mailer.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => 587, # ports 587 and 2525 are also supported with STARTTLS
:enable_starttls_auto => true, # detects and uses STARTTLS
:user_name => ENV["SENDGRID_USERNAME"],
:password => ENV["SENDGRID_PASSWORD"], # SMTP password is any valid API key, when user_name is "apikey".
:authentication => 'login',
:domain => 'yourdomain.com', # your domain to identify your server when connecting
}

Change default from: "Test Email" to valid email address, even example#example.com.

I would just like to point out, this is for sending emails via SMTP. While this method is totally ok, you should also consider sending via the API.
To do this, you need to specify an interceptor. Luckily, there's a Gem that helps with that. Here's a good article showing how to use it.
https://rubyplus.com/articles/561-Sending-Emails-using-SendGrid-API-in-Rails-4-1

It took us a long time to resolve the issue when we tried to deploy the SMTP relay on heroku. It worked perfectly fine on local but when pushed we received socket errors and time out issues. Eventually got it working.
Important note: Make sure not to use starttls_auto and SSL/or TLS this causes open SSL issue.

Related

Why can't I see any emails in my inbox sent from my Heroku Rails app using SendGrid SMTP Relay in development mode?

I'm trying to switch over to SendGrid from Mandrill in my Rails 4.2 app through SendGrid's SMTP Relay. I have set the 'To Email' to be my personal email address so that I can view the emails that have been sent, however none of the emails actually appear in my inbox despite the rails console claiming to have processed and sent the email.
I am fairly certain all my mailers have the appropriate smtp settings as I have mostly followed the instructions provided on the SendGrid website: https://sendgrid.com/docs/Integrate/Frameworks/rubyonrails.html
I have also tested my connectivity to SendGrid's SMTP Relay through telnet and the connection is succesful.
My SendGrid dashboard indicated that 0 emails have been sent. None of my emails appear under the Suppressions tab either so it's not like they have bounced or have been blocked.
This is in my config/environment.rb:
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
:password => ENV['SENDGRID_API_KEY'],
:domain => 'heroku.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
This is in my config/environments/development.rb:
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => 'smtp.sendgrid.net' }
This is the line in my controller that calls my ApplicationMailer:
ApplicationMailer.send_email(user, 'mypersonalemail#email.com', 'Test Subject').deliver
And this is what gets printed in the console when the mailer method is executed:
ApplicationMailer#send_email: processed outbound mail in 789.9ms
Sent mail to mypersonalemail#email.com (103.4ms)
But I still don't get any emails in my inbox or spam folder. Does anyone know how I can solve this? Thanks in advance.
Your domain and host options are wrong. Use localhost:3000 (unless you're using docker or something at which point replace localhost:3000 with 0.0.0.0:8000)
#/environments/development.rb
#Mailer Options
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'localhost:3000',
:enable_starttls_auto => true
}
config.action_mailer.default_url_options = { host: 'http://localhost:3000' }
config.action_mailer.asset_host = 'http://localhost:3000'
Make sure to add the sendgrid credentials to your local machine as environment vars. To get them, go to your heroku app and click on settings, then "reveal config vars". Then add those sendgrid credentials to your local machine as env. vars and you're done.

How do I send emails using Sendgrids API to send emails with rails 4? I can seem to put all the pieces together

I want to send emails with sendgrids API from a google cloud platform instance. They have a short tutorial on how to do this but it has the email message, who its from, who to send to, and other info all in app.rb which isnt the normal way messages are sent in rails apps.
I looked at the sendgrid ruby docs and they also dont have very good information. All the info in in one place and they dont state what files to put them in or even mention any smtp settings to use.
Here is what I have so far
development.rb
config.action_mailer.delivery_method = :smtp
# SMTP settings
config.action_mailer.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => 465,
:domain => "mydomain.com",
:user_name => ENV['sendgrid_username'],
:password => ENV['sendgrid_password'],
:authentication => :plain,
:ssl => true,
:enable_starttls_auto => true
}
gemfile
gem "sendgrid-ruby"
The email views are in app/views, the mailer methods are in app/mailer the same as normal rails 4 apps have it setup.
So I guess here are my main questions:
Where do I call the environment variables holding the sendgrid api key?
Where do I tell Action Mailer to use sendgrid or SendGrid::Mail as I've seen in a couple of places?
Do I even need the sendgrid gem?
Are the smtp settings correct for sending over SSL with sendgrid?
I'm new to sending emails like this in a rails app and would really appreciate the help.
Put apikey as the name and the actual apikey as password:
config.action_mailer.smtp_settings = {
address: "smtp.sendgrid.net",
port: 587,
domain: "yourwebsite.com",
authentication: :plain,
user_name: 'apikey',
password: Rails.application.secrets.sendgrid_api_key
}
Source
Use Figaro gem: https://github.com/laserlemon/figaro
It will generate an application.yml file for you, where you can store your sendgrid_username and sendgrid_password.
Have you generated your mailer? For example, generate mailer user_notifier where you can define your a default-from email, and some methods like this:
r
# send a signup email to the user, pass in the user object that contains the
user email address
default :from => 'hello#yourdomain.com'
def send_signup_email(user)
#user = user
mail( :to => #user.email,
:subject => 'Thanks for signing up!'
)
end
No, you don't need it.
https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/smtp_ports.html

Do I need to provide a "from" email address while using Heroku + SendGrid?

I have the standard setup in config/environments/production.rb
config.action_mailer.default_url_options = { host: "myapp.heroku.com" }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:addresses => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
However, I encountered the following error while trying to send a mail:
ArgumentError: An SMTP From address is required to send a message. Set the message smtp_envelope_from, return_path, sender, or from address.
I then tried using the email I found on my heroku add-on page, i.e. app#######heroku.com, but now I got
Errno::ECONNREFUSED: Connection refused - connect(2)
So do I need to specify a from email or not? If yes, which one should I use?
Try this code in your production.rb file:
config.action_mailer.default_options = { from: "my_address#example.com" }
Yes you need to set a from address. All emails need an from address specified.
:from => "address_you_are_sending_from#your_domain.com"
This needs to be set in your _mailer.rb file. You can also set it gloablly in an initiallizer but it must always be referenced in your_mailer.rb files, and within each mail method itself.
You should change the :domain to a domain that you control. But if you were to use Heroku would your apps address not be yourapp.herokuapp.com instead of yourapp.heroku.com?
You can set a from address in your mailer file.
For example if you have an admin_mailer.rb for notifying your personal email of new activity on your site, it could look like this:
def new_customer_trial(customer_object)
#new_customer = customer_object
mail :to => "me#personal_email.com", :subject => "New Customer Trial", :from => "'My Site Notifications' <notifications#my_site.com>"
end
And you'd send that mail from a controller:
AdminMailer.new_customer_trial(customer_object)
or as a delayed job:
AdminMailer.delay.new_customer_trial(customer_object)

Rails EOFError (end of file reached) when saving a devise user

I'm getting this error in production when trying to create a user (i'm using the devise gem).
EOFError (end of file reached):
I hit this problem before and it was due to my smtp settings using zoho mail.
I believe my configuration below is what fixed the problem:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.zoho.com",
:port => 465,
:domain => 'example.com',
:user_name => 'user#example.com',
:password => 'password',
:authentication => :login,
:ssl => true,
:tls => true,
:enable_starttls_auto => true
}
Now we've added SSL to the site and I believe that is what is causing this error to occur now.
Does anyone have any insight into this error or zoho mail smtp settings with SSL?
This error was caused by not having my config/initializers/devise.rb specifying the correct email address for config.mailer_sender.
Also! I made this additional mistake and had the same issue: I used my own domain instead of the mail server domain for the "domain" variable.
Your environment variable should be:
GMAIL_DOMAIN=gmail.com
Or for the example above:
:domain => 'gmail.com',
I found one cause for the error here => https://stackoverflow.com/a/40354121/6264112
But this didn't solve my issue. While I wasn't getting any errors, my emails were still not working through Zoho so I found another solution that works perfectly for my needs...
1) Connect Zoho to gmail using SMTP. I setup my zoho email as an alias for my personal gmail account so zoho emails are forwarded to gmail and I can reply to them IN gmail FROM my zoho email address. This should be done anyways so you never have to login to zoho. Just do all emailing from gmail.
2) Connect ActionMailer to gmail account NOT zoho.
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:user_name => ENV["gmail_username"],
:password => ENV["gmail_password"],
:authentication => :plain,
:enable_starttls_auto => true
}
Now, I just need to specify the to and from values in the mailer like so:
def notify_admin (message_details)
#message_details = message_details
mail(to: "jesse#mydomain.com", subject: "Contact form filled out by: " + message_details[:name], from: message_details[:email])
end
This works when I want to send emails to myself as is the example above when someone submits the contact form.
It ALSO works when I want to send an email from my domain such as when they fill out the lead magnet. All I did was switch the to: and from: addresses.
Here's a working pony gem call.
Pony.mail({
:to => 'apotonick#gmail.com',
subject: "Pony ride",
body: "Awesome!",
from: "nick#trb.to", # this MUST be the sending Zoho email.
:via => :smtp,
:via_options => {
:address => 'smtp.zoho.com',
:port => '465',
:enable_starttls_auto => true,
ssl: true,
:user_name => 'nick#trb.to', # MUST be identical to :from.
:password => 'yourStrongPw',
:authentication => :login,
}
})
I had this issue, and I tried everything and still couldn't figure out what the issue was.
Let's face it, it's a SH!t message. What I did find though I was running my rails app locally with POW and its actually a POW error.
When I run rails server and do the same thing that caused the error, I actually got the real error message and was able to find I hadn't setup my controller correctly

Net::SMTPAuthenticationError 502 5.5.2 in Rails ActionMailer

i'm trying to send confirmation email to the user.
But i get following error:
Net::SMTPAuthenticationError (502 5.5.2 Error: command not recognized
Configuration in production.rb is following:
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
# set delivery method to :smtp, :sendmail or :test
config.action_mailer.delivery_method = :smtp
# these options are only needed if you choose smtp delivery
config.action_mailer.smtp_settings = {
:address => 'path_to_address_specified_by_my_hoster',
:port => 25,
:domain => 'my_domain.com',
:authentication => :plain,
:user_name => 'signup#my_domain.com',
:password => 'password'
}
I have created a mailbox in user profile at my hosting provider, named "signup#my_domain.com"
For created mailbox, they issued to me login and password:
login = verbose_login
password = verbose_password
I did't completely understood the exact format of :user_name.
Should i use
:user_name => "signup#my_domain.com"
or:
:user_name => "signup"
or:
:user_name => "verbose_login"
Or this field is specific to the mail server, and i must ask support of hosting provider ?
And what the difference between :authentication => :plain and :login ?
Thanks.
This works well for me:
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:domain => 'gmail.com',
:user_name => 'my_nick#gmail.com',
:password => 'secret_password',
:authentication => 'login',
:enable_starttls_auto => true
}
more info here
Petr
I have got the same error recently, and the reason was incorrect format of recipients
recipient = IO.readlines(emails_filename).first
mail(:to => recipient, :subject => subject)
Don't forget to add strip to get clean email addresses.
I had the same problem, but it is just a google configuration issue.
For some reason Google was blocking access from unknown location (app in production), so to solve this you can go to http://www.google.com/accounts/DisplayUnlockCaptcha and click continue (this will grant access for 10 minutes for registering new apps).
On the other hand, you could login to your gmail account, then go to https://www.google.com/settings/security/lesssecureapps and enable the access to less secure applications, which was the solution for me!
Please try to login with browser once.
There might be some issue with login (it will ask captcha etc).
Once you successfully logged-in, then try with Rails Mailer.
It should work now.
This issue generally happens with test account as we do not login via browser usually.
Then mail providers ask for confirmation like captcha, dob or answer of security question etc.
You've to use ActionMaliler::Base instead of config
ActionMailer::Base.smtp_settings #try this
config.action_mailer.smtp_settings #instead of this
Change your smtp code to below. It should work now.
ActionMailer::Base.smtp_settings = {
:address => 'path_to_address_specified_by_my_hoster',
:port => 25,
:domain => 'my_domain.com',
:authentication => :plain,
:user_name => 'signup#my_domain.com',
:password => 'password'
}

Resources