I'm trying to send an email from rails and capture it using thunderbird.
This is my mailer:
def hello_world
from = 'bruno#localhost'
subject = 'Hello World'
to = 'bruno#localhost'
main to: to, from: from, subject: subject
end
I followed this instructions to configure thunderbird locally and it is working fine.
https://gist.github.com/raelgc/6031274
I'm not sure how to config rails.
What should I put here in development.rb ?
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => "localhost"
}
As #aniket-rao suggested: Use Mailcatcher which does all this. No need to install a local postfix server and fiddle with inboxes. From the docs:
MailCatcher runs a super simple SMTP server which catches any message sent to it to display in a web interface. Run mailcatcher, set your favourite app to deliver to smtp://127.0.0.1:1025 instead of your default SMTP server, then check out http://127.0.0.1:1080 to see the mail that's arrived so far.
In your Rails environment use this configuration to send email to Mailcatcher:
# use Mailcatcher
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: 'localhost', port: 1025 }
Your email will be visible on the local web app running on port 1080.
Try this
mail(to: to, from: from, subject: subject)
Related
I am trying to implement sendgrid into my backend api rails system so that when a user signs up I can send them a welcome email. After making a post request and handling user creation, I get this verification:
UserMailer#send_sign_up_email: processed outbound mail in 43.5ms
Sent mail to *******#gmail.com (185.8ms)
Date: Wed, 28 Feb 2018 16:54:05 -0800
From: *******#gmail.com
To: *******#gmail.com
Message-ID: <5a974f2d39c92_c5b2abcd76769fc423e0#albert-VirtualBox.mail>
Subject: Welcome to BottlesTonight albert jin!
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: quoted-printable
My code looks exactly like in this link https://sendgrid.com/docs/Integrate/Frameworks/rubyonrails.html.
This looks all fine and well, but the email is just not sending (I put stars here for the email but I actually put in my email, and I used another one of emails as the default for sending). There is no email in my outbox or inbox.
However, now that I think about it, I never "logged in" with my email or entered the password, so the application shouldn't have access to send emails with my email. I also never did anything with the api key that I made on my sendgrid account. Furthermore, for the environment.rb file, I wasn't sure what to put in domain, so I put gmail.com. These all seem kinda sketchy to me, I think the tutorial doesn't contain everything. Does anyone know how to configure this? I've been stuck on it for a while.
Edit:
I tried doing it on production and it is not working. Here is more info:
My production.rb looks like this:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => ENV['DEFAULT_HOST'] }
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
}
I have a heroku sendgrid add on. I have set the heroku config vars. In my registrations controller I merely added the line:
UserMailer.send_sign_up_email(#current_user).deliver
My mailer class looks like:
def send_sign_up_email(user)
#user = user
mail(to: #user.email, subject: "Welcome! #{#user.first_name}")
end
However, when I sign up on my website, the user gets added to the database but the email is not sending. Does anyone know why, or how I can debug?
I would suggest to remove all config for ActionMailer from your environment files (i.e. files under /config/environments), except following ones
# Don't care if the mailer can't send.
config.action_mailer.perform_caching = false
# Reference: http://stackoverflow.com/a/20770131/936494
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
Then create an initializer /config/initializers/mail_config.rb and add following code to it:
TEST_ENVS = %w(test)
FILESYSTEM_ENVS = TEST_ENVS + %w(development)
# =========== DELIVERY METHOD SETTING
delivery_method = case Rails.env.to_sym
when :production, :staging, :experimental
:sendmail
when :test
:test
else
:smtp
end
ActionMailer::Base.delivery_method = delivery_method
# =========== SMTP SETTINGS
ENVS_TO_USE_GMAIL_CONFIG = %w(development test)
gmail_config = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: ENV['MAIL_USER_NAME'],
password: ENV['MAIL_PASSWORD'],
authentication: :plain,
enable_starttls_auto: true
}
if :smtp == delivery_method
use_gmail_config = ENVS_TO_USE_GMAIL_CONFIG.include?(Rails.env)
smtp_settings = ( use_gmail_config ? gmail_config : {} )
ActionMailer::Base.smtp_settings = smtp_settings
end
# =========== DEFAULT URL OPTIONS
default_url_options_settings = Settings.default_url_options
host = default_url_options_settings.host
port = default_url_options_settings.port
protocol = default_url_options_settings.protocol
default_url_options = {}
default_url_options[:host] = host if host.present?
default_url_options[:port] = port if port.present?
default_url_options[:protocol] = protocol if protocol.present?
ActionMailer::Base.default_url_options = default_url_options
The Settings object is available as part of using config gem. If you do not want to use that gem for configuring env-specific values then you can just hard-code them in the initializer and try it.
My /config/settings.yml looks like
default_url_options:
host: ''
port: ''
protocol: ''
and my /config/settings/development.yml looks like
default_url_options:
host: 'localhost'
port: '3000'
Having a centralized mailer config helps in diagnosing mailer settings related issues in quick manner.
First try it for Gmail account and if it works you can be sure that sending email works. Just make sure in your Gmail account Less Secure Apps setting is enabled.
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.
I have rails app which uses devise ofr authentication and sidekiq for background email jobs. All of a sudden, in development only, I am getting the following error associated with an attempt to send an email from the app (e.g. devise forgotten password)
EOFError: end of file reached
Strangely the app in production works (heroku set up using sendgrid). I haven't changed any of my development email settings....
ActionMailer::Base.default :from => 'slfwalsh#gmail.com'
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => '#gmail.com',
:user_name => "xxxxx#gmail.com",
:password => "xxxxxxxx",
:authentication => 'plain',
:enable_starttls_auto => true
}
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
I can't find anything to address this online. Also I note that ALL my apps in development, using similar settings are throwing the same error. I tried a different email address and password (again gmail) and no luck....
For those like Aleksey wondering how the problem was solved, he added a valid domain. Went from domain: '#gmail.com' to domain: "myprojectdomain.com"
For me, setting sender email in my Devise config file fixed the issue.
I have got EOFError: end of file reached issue after migration from EC2 to ECS deployment.
Following is short way to diagnose issue.
$ telnet smtp.sendgrid.net 587
Trying 167.89.118.51...
Connected to smtp.sendgrid.net.
Escape character is '^]'.
220 SG ESMTP service ready at ismtpd0009p1las1.sendgrid.net
...
In case when you don't see kind of 220 greeting from the server after connection, it may mean that something sitting between your client and SMTP server and blocks connection. In our case it was AppMesh proxy which is blocking smtp.
Next test is
openssl s_client -crlf -starttls smtp -connect smtp.sendgrid.net:587
which should show a lot info about SSL.
If you can't see expected info by this tests check your infrastructure first, neither smtp settings will work.
Note that 587 is standard replacement for 25. It is expected that client send STARTTLS to obtain SSL connection. While another alternative - 465 expected to connect with SSL by default.
More details: https://aws.amazon.com/premiumsupport/knowledge-center/smtp-connectivity-timeout-issues-ses/
For those who are stuck....this worked but I unclear why.
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: "myprojectdomain.com",
user_name: "xxxx#gmail.com",
password: "xxxx",
authentication: 'plain',
enable_starttls_auto: true
}
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
I had this same issue. The problem was that I was using the Imap host setting (imap.gmail.com) for Smtp host setting (smtp.gmail.com).
Here's how I solved it:
I simply replaced the host
imap.gmail.com
with
smtp.gmail.com
That's all.
I hope this helps.
I would like to use Sendgrid to manage outgoing emails from a 3.2.2 version rails app I am developing with the help of a friend. She has email working from within the app using gmail, on her local/dev build. I need sendgrid up and running.
I cannot even get it to work locally.
From my development.rb file
config.action_mailer.default_url_options = { :host => 'localhost:3030' }
config.action_mailer.smtp_settings = {
:user_name => ENV['EMAIL_USERNAME'],
:password => ENV['EMAIL_PASSWORD'],
:domain => 'myapplicationdomain.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => 'plain',
:enable_starttls_auto => true
}
config.action_mailer.delivery_method = :smtp
Then I have a variable file in the root of my application that includes the following:
export EMAIL_USERNAME=sendgridusername
export EMAIL_PASSWORD=sendgridpassword
export MAIL_TO=report#myapplicationdomain.com
Here is the code from my mailer
class StatusMailer < ActionMailer::Base
default from: "reports#myapplicationdomain.com"
def status_report(report)
#greeting = "Hello"
#report = report
if ENV['MAIL_TO']
email = ENV['MAIL_TO'] if ENV['MAIL_TO']
else
email = #report.user.email
end
#statuses = #report.statuses
#reviewers = #report.user.reviewers
bcc = []
#reviewers.each do |reviewer|
bcc.append(reviewer.email)
end
#bcc = bcc
mail(to: email, bcc: bcc, subject: 'Status Report')
end
end
Am I missing some other setting? What about the MAIL_TO field in the variable, I am not certain what that should be set to, or if it even needs to be declared.
Is there another file that I should be editing? I had this working several days ago, but functionality somehow slipped away :0
Rails server says that emails were sent, but sendgrid has no record; nor are the emails being received by addresses on the distribution list.
Thank you in advance for any assistance.
Do you have the following settings in your config/environments/development.rb?
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
If not, add them to your config file and restart your server.
Update:
This error suggests that you're not authenticated. Are you sure the values of your ENV['EMAIL_USERNAME'] and ENV['EMAIL_PASSWORD'] variables are present/correct?
This post:
Sendgrid / email sending issues in Ruby on Rails (hosted on Heroku)
Got me up and running. The key being putting the SMTP and sendgrid information in the environment.rb file.
I can't explain exactly why that made the difference, but it did.
I have a Rails app configured to use Amazon SES via SMTP. When I try and send email, though, it appears to timeout after a minute, and I get an EOFError. It smells like a configuration issue--the email seems to be constructed fine, and I can send myself test emails from the AWS SES console. This is in sandbox mode, and the app is running in development mode, but both the sending and receiving emails have been verified with SES, and development.rb is set up with this:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
I've tried a million config variations; this is starting to drive me bananas. Any help or guidance would be very, very appreciated. More details:
The smtp config, which I have in an initializer:
ActionMailer::Base.smtp_settings = {
:address => "email-smtp.us-east-1.amazonaws.com",
:port => "465",
:authentication => :plain,
:enable_starttls_auto => true,
:user_name => "1234",
:password => "abcde"
}
The logs with the error, a bit truncated for brevity:
Sent mail to john#phu.com (59929ms)
Date: Tue, 20 Dec 2011 03:08:37 -0800
From: contact#phu.com
To: john#phu.com
Message-ID: <4ef06cb5ed3c_d73c3fc604c34d4491943#Johns-MacBook-Pro.local.mail>
Subject: Your invitation to Phu
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<!DOCTYPE html>
....
Completed 500 Internal Server Error in 60564ms
EOFError (end of file reached):
app/controllers/admin_controller.rb:61:in `block in send_invite'
app/controllers/admin_controller.rb:46:in `send_invite'
There is also a solution without the monkey-patch solution from Mihir (which, according to AWS SES documentation, http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/SMTP.Connecting.html, is the TLS wrapper solution), by using port 587 and :enable_starttls_auto option (the STARTTLS solution). So the modified config is such:
config.action_mailer.default_url_options = { host: “<example.com>” }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address: “email-smtp.us-east-1.amazonaws.com”,
:port: 587,
:domain: “<example.com>”,
:authentication: :login,
:user_name: “<your aws smtp username>”,
:password: “<your aws smtp password>”,
:enable_starttls_auto => true
}
Here is a solution in case you want to use SMTP (and not the AWS-SES gem)
http://blog.readypulse.com/2012/01/06/amazon-ses-smtp-emails-using-rails-3-1-in-three-easy-steps/
Things to note
AWS SMTP only works on TLS
AWS SMTP does NOT support STARTTLS
ActionMailer’s configuration does not have an easy TLS switch.
Steps to follow
Enable SMTP support on your AWS Console – See instructions here.
Create an initializer under your config/initializers directory. I am calling it amazon_ses.rb and add following code to money patch ActionMailer’s SMTP settings.
module Net
class SMTP
def tls?
true
end
end
end
Add following code in your development.rb and production.rb files. Modify the settings to match your environment.
config.action_mailer.default_url_options = { host: “<example.com>” }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: “email-smtp.us-east-1.amazonaws.com”,
port: 465,
domain: “<example.com>”,
authentication: :login,
user_name: “<your aws smtp username>”,
password: “<your aws smtp password>”
}
I ran into this same issue using Rails 2.3, with Ruby 1.8.7, in dev mode with a sandboxed SES account, sending to/from verified senders.
I worked around it by adding in the unofficial aws-ses gem. Stick it in your Gemfile, and then replace the smtp settings with these 5 lines:
# Configure mail sending options: Use AWS-SES for all environments
config.after_initialize do
ActionMailer::Base.delivery_method = :amazon_ses
ActionMailer::Base.custom_amazon_ses_mailer = AWS::SES::Base.new(:secret_access_key => 'asfd/1234', :access_key_id => 'ABCD')
end
Sending then worked as expected…which tells me the emails themselves were getting set up correctly.
I've done a lot of googling, and haven't seen any confirmation that SES-SMTP is compatible with Rails 2.3 + Ruby 1.8.7. Nor have I found anything that explicitly denies it either, beyond your & my experience.
Let us know if you find a solution!
SES requires a SSL session before the EHLO command is sent.
I know System.Net.Mail doesn't work with SES, because System.Net.Mail initiates the TLS after the SMTP session has started.
I got this working on Rails 3.2.12 adding require 'net/smtp' to the initializer file with the module change like:
require 'net/smtp'
module Net
class SMTP
def tls?
true
end
end
end