Sending emails with pure Ruby - ruby-on-rails

I have problems with sending emails with pure Ruby. Here is how my script looks like:
Mail.defaults do
delivery_method(
:smtp,
address: 'smtp.sendgrid.net',
port: 587,
user_name: 'sendgrid_username',
password: 'sendgrid_password',
authentication: :login,
enable_starttls_auto: false,
openssl_verify_mode: "none"
)
end
Mail.deliver do
from 'Test Email'
to 'user#example.com'
subject 'Here is the image you wanted'
body "Test Email"
end
This script raise the following error:
/Users/mateuszurbanski/.rubies/ruby-2.7.2/lib/ruby/2.7.0/net/smtp.rb:975:in `check_auth_response': 535 Authentication failed: Bad username / password (Net::SMTPAuthenticationError)
I'm using credentials from one of my Ruby on Rails project and they are fine. Any ideas?

Sendgrid recently transitioned to api keys and will reject plain auth, see details here.
Your old credentials while still being valid may not be accepted.
Generate a new api key in sendgrid and use it in place of password. Username will be apikey

Instead of using your SendGrid username and password in this config, use the following,
user_name: 'apikey',
password: '<sendgrid_api_key>',
This works for me when defining the smtp settings for ActionMailer, so it should work here as well.

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
}

Microsoft Exchange Server - Ruby on Rails

My configuration for sending mails in Thunderbird for this exchange server email account is as follows:
server name: pod51003.outlook.com
port: 587
username: my email address
authentication method: normal password
connection security: STARTTLS
I am trying to send email from my rails application, my configuration in my application is as follows:
config.action_mailer.smtp_settings = {
address: "pod51003.outlook.com",
port: 587,
authentication: "plain",
:enable_starttls_auto => 'true',
user_name: 'myemail',
password: 'mypassword'
}
I have tried different authentication methods such as none and login. I have tried the gem ruby-ntlm and set ntlm as the authentication method too but I keep getting the error:
504 5.7.4 Unrecognized authentication type
Try changing the authentication setting to :login

ActionMailer with SMTP - Bad recipient address syntax

My user has email with this format: "-user-#domain.com". Mailgun validation succeeded but Rails couldn't send email to the address. I'm using SMTP with Mandrill.
This is the error message:
/home/johnny/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/net/smtp.rb:948:in `check_response': 401 4.1.3 Bad recipient address syntax (Net::SMTPServerBusy)
Do you have any idea?
Thanks in advance.
Updated:
This sample code (with valid SMTP configuration) would raise the error:
#!/usr/bin/env ruby
require 'mail'
options = {
address: "smtp.mandrillapp.com",
port: 587,
domain: "mydomain.com",
authentication: "login",
user_name: "myemail#mydomain.com",
password: "mypassword",
enable_starttls_auto: false
}
Mail.defaults do
delivery_method :smtp, options
end
Mail.deliver do
from 'valid.email#domain.com'
to "-test-#domain.com"
subject 'Testing sendmail'
body 'Testing sendmail'
end
Even if the starting dash in the email address is valid, most mail servers do not accept such emails due to restrictions for command line arguments.
A quick fix you can try is wrapping the email address with angle brackets:
Mail.deliver do
from 'valid.email#domain.com'
to "<-test-#domain.com>"
subject 'Testing sendmail'
body 'Testing sendmail'
end

sender email is being overridden by smtp settings user_name

i am writing a ruby script to send email using 'mail' gem.
and my smtp settings on my local machine:
mailer_options:
address: smtp.gmail.com
port: 465
domain: gmail.com
user_name: example#gmail.com
password: example_password
authentication: :login
enable_starttls_auto: true
ssl: true
i am trying to send the like this :-----
Mail.deliver do
to 'receiver#gmail.com'
from 'sender#gmail.com'
subject 'Test Mail'
text_part do
body 'Hello World!!!!!'
end
end
the mail is send successfully but when i open the email i see sender email id as
example#gmail.com instead of sender#gmail.com, why it is so i am not able to figure out.
thanks for any comment and answers.
This is often done by your SMTP server and is beyond your control. You could try using a different SMTP provider like Sendgrid if Google isn't working out for you.
Correct answers above, it's not your code, it's the Gmail SMTP servers that do this. I work for SendGrid and if you wanted to change this over to using SendGrid (or any other provider for that matter) then you can do it really easily. Our free plan can send 400 emails a day and is fine for local development.
Your code would change as follows:
mailer_options:
address: smtp.sendgrid.net
port: 587
domain: yourdomain.com
username: your_username
password: your_password
authentication: plain
enable_starttls_auto: true
You don't need to have SSL set at this stage. From here you can use your original Mail.deliver method.
You'll find you can now send from the sender#yourdomain.com address, or whichever address you specify in the from attribute.
There's further Ruby & SendGrid details in the SendGrid documentation.
google does not allow sender email masking. This is done by GMAIL's server. Not by your rails code!!. It always uses email address of gmail account you are using as "from_email".
Your best alternative might be "Mandrill" (12000 emails free / month). They allow email routing in the way you want.
Please set sender default name instead of 'sender#gmail.com' at below :
class UserMailer < ActionMailer::Base
default from: 'sender#gmail.com'
def welcome_email(user)
#user = user
#url = 'http://example.com/login'
mail(to: #user.email, subject: 'Welcome to My Awesome Site')
end
end

Resources