Sending an email from my ROR4 app - ruby-on-rails

I know the question has been asked before, but I still can't get it to work, even though the console is saying it has.
emailer.rb
class Emailer < ActionMailer::Base
default from: "from#example.com"
def welcome_email()
#url = 'http://example.com/login'
email_with_name = "#{My Name} <#{MyEmail#gmail.com}>"
mail(to: email_with_name, subject: 'Test')
end
end
environment.rb #(in config)
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: 'myemail#gmail.com',
password: 'mypassword',
authentication: 'plain',
enable_starttls_auto: true }
To test, I'm putting Emailer.welcome_email().deliver into the console
I'm told that if my setting are incorrect, it's possible that no error comes up.
Do these settings look ok to everyone? If so, where else might I check to find the problem?
Thanks

I was having the same issue as you. All the data appeared to be passing through but no email was getting sent. I was actually seeing a Connection error in my server log which to me indicated an inability of my app to connect to Google.
I ended up finding this instruction set http://www.leemunroe.com/send-automated-email-ruby-rails-mailgun/ and creating a free MailGun account. It was really straight-forward. Had it up and running within about 30 minutes, as opposed to the hours I spent failing with Google + SMTP.
Hope this helps. Good luck.

Related

Seding emails with Devise gem and Mailgun Api

I want to send automated emails via Mailgun either SMTP or API. The problem is that in tutorials I find they explain how to do that manually e.i creating mailer class etc. For example like that:
def send_simple_message
RestClient.post "https://api:YOUR_API_KEY"\
"#api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
:from => "Excited User <mailgun#YOUR_DOMAIN_NAME>",
:to => "bar#example.com, YOU#YOUR_DOMAIN_NAME",
:subject => "Hello",
:text => "Testing some Mailgun awesomness!"
end
This is from official Mailgun documentation.
But I am using Devise gem which has email sending implemented.
For example I want to send password reset email. When I click forgot password and submit my email from logs I see that my email is tried to be sent, but not sent of course, I need to set up email server.
So the question is where is this code for sending recovery email is written in devise, how to override it? I want it to oveeride so it will use Mailgun API for example.
I have already generated registrations_controller.rb using
rails generate devise:controllers registrations
command. So I suppose I am overriding it here?
Any suggestions?
have you read this tutorial? Looks like you need to setup it in config/environments/development.rb
Something like:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: ENV['GMAIL_DOMAIN'],
authentication: 'plain',
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD']
}
Also, you can try to use mail gun gem. Looks like It's really easy to setup it
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: '<mailgun api key>',
domain: '<mailgun domain>'
}
Hope it helps you.

Ruby on Rails: bad username / password? (535 Auth failed)

I just finished my ruby foundations coursework at Bloc and I'm starting to bury my head into rails development. Things were going smooth until I hit this snag with devise and confirmation emails. I tried googling and looking around at some other questions but couldn't really find any that gave me anything that I could pull from and apply to my situation.
I'm receiving the following error when signing up for an account.
Net::SMTPAuthenticationError in Devise::RegistrationsController#create
535 Authentication failed: Bad username / password
Error extracted from source around line #976
def check_auth_response(res)
unless res.success?
raise SMTPAuthenticationError, res.message
end
end
From other posts I know you'll probably want to see that I have a config/initializers/setup_mail.rb file that looks like this:
if Rails.env.development?
ActionMailer::Base.delivery_method = :smtp
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
}
end
And here's an application.yml file EXAMPLE:
SENDGRID_PASSWORD:
SENDGRID_USERNAME:
SECRET_KEY_BASE:
also I have the following in my config/environments/development.rb before anybody suggests it:
config.action_mailer.default_url_options = { host: 'localhost:3000'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
# Override Action Mailer's 'silent errors' in development
config.action_mailer.raise_delivery_errors = true
If there's any other files that you'd like to see let me know and I'll add them to this post.
Congrats and welcome to the world of hacking on cool things.
The error you are getting means that the SendGrid server received a bad username + password combo.
Chances are your environment variables are empty and your application.yml file isn't being loaded properly with your SendGrid username + password.
You can confirm this by printing them out somewhere in your code. In a controller works.
puts "SENDGRID_USERNAME: #{ENV['SENDGRID_USERNAME']}"
puts "SENDGRID_PASSWORD: #{ENV['SENDGRID_PASSWORD']}"
I'd suspect that they are nil.
I'd recommend reading https://quickleft.com/blog/simple-rails-app-configuration-settings/ about how to get them sourced into your app.
Please let me know if you need any more help!
Two-Factor Authentication is required as of Q4 2020, and all Twilio
SendGrid API endpoints will reject new API requests and SMTP
configurations made with a username and password via Basic
Authentication.
I received a similar issue from an app I've been running for the last couple years. From now on, basic auth doesn't work, and you'll need to use an alternative auth mechanism. Heroku sendgrid auto-configuration on installation has not yet been updated to reflect this.
Source: https://sendgrid.com/docs/for-developers/sending-email/upgrade-your-authentication-method-to-api-keys/
In my case the error was to use as username the id of my apikey, but this is wrong, the correct value user_name is 'apikey', (Literally 'apikey' string), as they say in their integration example,
https://sendgrid.com/docs/for-developers/sending-email/rubyonrails/
https://app.sendgrid.com/guide/integrate/langs/smtp
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey', # This is the string literal 'apikey', NOT the ID of your API key
:password => '<SENDGRID_API_KEY>', # This is the secret sendgrid API key which was issued during API key creation
:domain => 'yourdomain.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}

Devise, admin_mailer & config

I'm using devise with my rails 4 app.
I'm trying to setup figaro before I let the site go live, but for now, I'm managing my test email account with my passwords in production.rb. It won't be this way for long, but I have hit a problem with my setup.
I have two admin_mailer emails that get sent when someone registers. One is an email to me, using one gmail account to let me know that they have registered. The second is an email to the user, welcoming them to the site. It is supposed to be sent from a second email account that I set up.
In my production.rb, I have:
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: ###,
domain: 'gmail.com',
user_name: 'firstemailaddress#gmail.com',
password: '###',
authentication: 'plain',
enable_starttls_auto: true }
{
address: 'smtp.gmail.com',
port: ###,
domain: 'gmail.com',
user_name: 'secondemailaddress#gmail.com',
password: '####',
authentication: 'plain',
enable_starttls_auto: true }
In my admin_mailer, I set the sender for the emails as one or the other of those user names.
However, when I run the code, both emails are sent from the first email address.
Does anyone know how to set up to mailers so that emails send from different addresses?
Thank you
I think each mailer is supposed to be associated with one email account. You could create two separate mailers, and define the smtp settings within each individual mailer rather than in production.rb.
For example, app/mailers/first_mailer.rb :
class FirstMailer < ActionMailer::Base
default from: 'firstemailaddress#gmail.com'
self.delivery_method = :smtp
self.smtp_settings = {
# your gmail smtp settings here
}
def some_email(user)
mail(to: user.email, subject: 'Subject')
end
end
You can send this by calling FirstMailer.some_email(user).deliver.
Similarly, you then create another file app/mailers/second_mailer.rb that uses a different account (and so different settings).
There may be a more DRY way to do this, but I know this works.

Running into SMTP error when trying to send email in RoR app

I've been desperately trying to send an email using the Action Mailer class in RoR, and even though the terminal shows that a message is being sent, it keeps returning with this error:
et::SMTPAuthenticationError: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbtOS
from /Users/abhasarya/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/smtp.rb:968:in `check_auth_response'
from /Users/abhasarya/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/smtp.rb:739:in `auth_plain'
from /Users/abhasarya/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/smtp.rb:731:in `authenticate'...
Here's what my mailer class looks like within app/mailers/my_mailer.rb:
class MyMailer < ActionMailer::Base
default from: "from#example.com"
def welcome_email(user)
#user = user
mail(to: user.email,
from: 'example_email#gmail.com',
subject: 'Welcome!')
end
end
And here's what my config/application.rb file looks like:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
#domain: 'gmail.com',
user_name: 'example_email#gmail.com',
password: 'my_password',
authentication: 'plain',
enable_starttls_auto: true
}
config.action_mailer.default_url_options = {
:host => "localhost",
:port => 3000
}
in my config/environments/development.rb file I also have these two lines:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
My problem is that whenever I start the rails console (working in development, have no idea how to run in production), assign a user's email to the user variable then enter the command: MyMailer.welcome_email(user).deliver
the terminal says:
Rendered my_mailer/welcome_email.html.erb (11.7ms)
Rendered my_mailer/welcome_email.text.erb (0.5ms)
Sent mail to abhas.arya#yahoo.com (923.1ms)
Date: Fri, 08 Aug 2014 13:54:38 -0400
From: abhas.aryaa#gmail.com
To: abhas.arya#yahoo.com
Message-ID: <53e50ededebb2_2b0b8082dbf8507c5#Abhass-MacBook-Pro.local.mail>
Subject: Welcome!
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_53e50eded7355_2b0b8082dbf85068f";
charset=UTF-8
Content-Transfer-Encoding: 7bit
but then renders the error. My views are simple enough that I didn't think I needed to include them here. I've desperately tried everything, including unlocking google captcha but still nothing works. I'd appreciate any help, all I want is for an email to get sent to the proper inbox. I'd love you forever if you can solve this issue!!!
The reason that you are seeing this error is that Google has blocked your IP. You will need to enable authorization for this IP.
Go to http://www.google.com/accounts/DisplayUnlockCaptcha and click continue.
Then again try to send email from the application, it should work. You will need to send email from your app within 10 min of visiting the above link. By visiting above link, Google will grant access to register new apps for 10 min.
I solved by doing the following:
1) Log into the Google Apps Admin portal and enable Less Secure Apps by checking "Allow users to manage their access to less secure apps" under Security preferences.
2) Login into the account that will serve as the mailer and turn "Allow less secure apps" to ON.
Most of the answers available on-line refer to step 2, but you cannot configure at a user level without the Admin turning the feature on.
This one solved the issue for me after some investigation:
Click https://www.google.com/settings/u/0/security/lesssecureapps
Enable access for less secure apps here by logging in with the email address you have provided in smtp configuration.
I resolved my issue by doing this.
config.action_mailer.default :charset => "utf-8"
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'mysite.com',
user_name: myemail#gmail.com,
password: mypassword,
authentication: 'plain',
enable_starttls_auto: true
}
As google will try to block your sign-in if you have turned off access for less secure apps in your accounts settings. Therefore, follow this link and "Turn on" access for less secure apps.

Devise registration confirmation email delivered 20 minutes late + What delivery method does Devise mailer use?

I have two problems I have been wasting a lot of time on for the past 3 days. I would really appreciate experienced coders helping me out here,.
I have a model User that I send a confirmation email using Devise invitable from the registration controller.
User.invite!({:email => email, ...)
Now I have these settings
In config/environments/development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
address: 'mail.myapp.com',
port: 26,
domain: 'myapp.com',
user_name: 'notifications#myapp.com',
password: 'xxxx',
authentication: 'plain',
enable_starttls_auto: true,
openssl_verify_mode: 'none'
}
and config/devise.rb
config.mailer_sender = 'notifications#myapp.com'
This mail is delivered exactly 20 minutes later after the debug output says "Sent email to ..."
Now I also use a custom NotificationsMailer else where in the code, where I send notification emails other than the devise based registration process. I have the same settings as above entered in config/initializers/setup_mail.rb and in this case, the mails are delivered instantaneously.Why this delay?
Question/doubt #2
I figured if I could intercept the delivery process of sending the mail, I would be able to check the Mail::Message object through logging and later develop an asynchronous way of handling using Sidekiq.
So in config/application.rb
ActionMailer::Base.add_delivery_method :queued, :QueuedDelivery
In config/environments/development.rb
config.action_mailer.delivery_method = :queued
In lib/queued_delivery.rb
class QueuedDelivery
def deliver!(mail)
logger.debug "mail object string rep: #{mail.to_s}"
logger.debug "mail object settings: #{mail.deliver_method.settings}"
end
end
In spite of changing the delivery method, it's weird Devise still sends the mail which arrives 20 minutes late as usual and I cant see the debug level logging that I put above.
How is Devise sending these emails?! I checked devise_mail() in the devise gem, and it uses this code finally mail headers_for(action, opts). What is going on here?

Resources