ActionMailer with SMTP - Bad recipient address syntax - ruby-on-rails

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

Related

Rails ActionMailer sends email but it does not show up as a sent email in the mailbox used

I am using namecheap to send emails and it uses privateemail.
My setup in ActionMailer is:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
address: 'mail.privateemail.com',
port: 587,
domain: 'privateemail.com',
user_name: 'very#cool.com',
password: "very_secret",
authentication: 'plain',
enable_starttls_auto: true
}
As they say here:
https://www.namecheap.com/support/knowledgebase/article.aspx/1179/2175/general-private-email-configuration-for-mail-clients-and-mobile-devices/
Now it sends the emails, but when I login in the web client, it does not show any mails sent in the sent folder.
Why is that ?
SMTP delivery means sending an email and not send an email and store it in sent folder. This has to be done by the client additionally!

Sending emails with pure Ruby

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.

How to send an email with mail gem in ruby on rails

I am trying to send an email using mail gem. But Unfortunately it is not working.
This is my controller.
def create
fn = params["firstname"]
ln = params["lastname"]
email = params["email"]
file = params["file"]
summery = params["summery"]
email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
mail = Mail.new do
from 'someone#gmail.com'
to email
subject "Saying Hi"
body email_body
end
mail.add_file(filename: file.original_filename, content: File.read(file.tempfile.path)) unless file.nil?
mail.deliver!
render json: {message: "A bug has been created", success: true}, status: 201
end
This code is producing this error
Errno::ECONNREFUSED - Connection refused - connect(2) for "localhost" port 25:
However when I am installing the mailcatcher and configure my controller to send the mail to mailcatcher, I can see the email in my mailcatcher UI.
Mail.defaults do
delivery_method :smtp, address: "localhost", port: 1025
end
Also I have add this two lines to my config/environment/development.rb
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
From my searches I saw that some people are mentioning that dont send email on development mode, however on this case I really want to test the full capability.
Update
As #Uzbekjon and #SimoneCarletti suggested I change my code to use the ActionMailer. I created the a file in app/mailer/ and I am calling that from my controller.
def create
fn = params["firstname"]
ln = params["lastname"]
email = params["email"]
file = params["file"]
summery = params["summery"]
email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
WelcomeMailer.welcome(fn, ln, email, file, email_body).deliver_now
render json: {message: "An Email has been send", success: true}, status: 201
end
and This is my mailer
class WelcomeMailer < ActionMailer::Base
default from: "someone#yahoo.com"
def welcome(first_name, last_name, email, file, email_body)
attachments["#{file.original_filename}"] = File.read("#{file.tempfile.path}")
mail(
to: email,
subject: 'Welcome to My Awesome Site',
body: email_body
)
end
end
However I am still getting the same error.
Errno::ECONNREFUSED - Connection refused - connect(2) for "localhost" port 25:
Answer
So I found the solution. Yes you need to use the ActionMailer. After that you need to go to the config/environments/development.rb , and modify and add these lines:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "YOUR EMAIL",
:password => "YOUR Password",
:authentication => "plain",
:enable_starttls_auto => true
}
Also If Gmail complained about this:
Net::SMTPAuthenticationError - 534-5.7.9 Application-specific password required
Go to this link and let less secure application access Gmail.
Other configurations are available for other services like Yahoo. Just Google it.
Errno::ECONNREFUSED - Connection refused - connect(2) for "localhost" port 25:
Looks like mail gem is trying to connect to your local smtp server on port 25. Most probably you don't have the service running and receiving connections on port 25.
To solve, install and run sendmail or postfix on your machine.
PS. Use ActionMailer.
You don't have a mail server running on port 25. You can install postfix and start the server using
sudo postfix start
And then modify the settings in config/environments/development.rb
config.action_mailer.delivery_method = :sendmail
Hope this helps.

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
}

Resources