Cloud9 and ActionMailer / Mailgun? - ruby-on-rails

I hope you can lend me a hand with this!
I used to develop locally, but I'm abroad and I'm using Cloud9 to work with some projects. Currently, It's giving me a hard time with Action Mailer.
My ActionMailer Initializer:
ActionMailer::Base.smtp_settings = {
port: '2525',
address: 'smtp.mailgun.org',
user_name: ENV['MAILGUN_SMTP_LOGIN'],
password: ENV['MAILGUN_SMTP_PASSWORD'],
domain: 'app07ad98bdda3b4c469a24228512cffe5c.mailgun.org',
authentication: :plain,
content_type: 'text/html'
}
ActionMailer::Base.delivery_method = :smtp
mailers/gun_mailer.rb
class GunMailer < ActionMailer::Base
default from: "from#example.com"
def welcome_email(user)
#user = user
#url = 'http://example.com/login'
mail(to: #user.email, subject: 'Welcome to My Awesome Site')
end
end
views/gun_mailer/welcome_email.erb
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to example.com, <%= #user.email %></h1>
<p>
You have successfully signed up to example.com,
your username is: <%= #user.email %>.<br>
</p>
<p>
To login to the site, just follow this link: <%= #url %>.
</p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>
Console
u = User.first
GunMailer.welcome_email(u).deliver
I've set up the environment variables with figaro, and evrything seems to be correct... But the mail is never sent! I've heard that C9 has some ports blocked (587 being one of them), I've tried with 2587, 2525 (as other posters recommended), but It doesn't work!

First, I would make sure that the following variables are actually being set within your mail.rb using the Rails console:
ENV['MAILGUN_SMTP_LOGIN']
ENV['MAILGUN_SMTP_PASSWORD']
Second, you should verify that the ports are not blocked by doing the following:
$ telnet smtp.mailgun.org 2525
$ telnet smtp.mailgun.org 587
Note: The port isn't blocked if you see something similar to the following:
Trying 104.130.177.23...
Connected to smtp.mailgun.org.
Escape character is '^]'.
220 ak47 ESMTP ready
If one of the above ports are not blocked, then I would stop here, update mail initializer to use the unblocked port, and recheck your code. Otherwise, I would continue reading.
Third, if you have determined that both ports are blocked, then you'll need to use the HTTP API and I would read the documentation here:
https://documentation.mailgun.com/api-sending.html#sending
or
using a different hosting company like Heroku.com or DigitalOcean.com.
Well, I wish that the information above assists you in sorting out your issue.

Related

Action mailer - Sending an email through a contact form with Ruby on Rails

I'm using Ruby 2.6.3 and Rails 5.2. I want to make a contact form on my website, with a box for user email address, and a box for the message content. When a user fill those boxes and click on "Submit", i would like that it send me an email. No need for the user to sign up or anything.
My website is a one page website, i don't have any models, and i just have 1 controller : pages_controller.rb.
I used the documentation on Action mailer but i didn't suceed.
Here are the steps i followed :
rails generate mailer ContactMailer
config/environments/development.rb :
config.action_mailer.default charset: 'utf-8'
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.mail.yahoo.com",
port: 465,
domain: "yahoo.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: "myemailaddress#yahoo.com",
password: "********"
}
app/mailers/contact_mailer.rb :
class ContactMailer < ApplicationMailer
default from: "from#example.com"
def contact(message)
#message = message
mail(to: 'myemailaddress#yahoo.com', subject: 'Test')
end
end
app/views/contact_mailer/contact.html.erb :
<p>Hello world</p>
<%= #message %>
app/controllers/pages_controller.rb :
class PagesController < ApplicationController
def home
end
def send_contact
ContactMailer.contact(params[:message]).deliver
end
end
app/views/pages/home.html.erb :
<form action="/send_contact" method="post">
<input name="email" type="email" class="form-control mb-1" placeholder="Your email">
<textarea name="message" class="form-control" placeholder="Your message"></textarea>
<button type="submit">Submit</button>
</form>
config/routes.rb :
Rails.application.routes.draw do
root to: 'pages#home'
post "send_contact" => "pages#send_contact"
end
This is supposed to send me an email when clicking on submit. Instead, i get this error : EOFError in PagesController#send_contact end of file
So i tried with a gmail address with the right username / password and the right config :
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
authentication: "plain",
user_name: ENV["USERNAME"],
password: ENV["PASSWORD"]
}
And i have this error : 535-5.7.8 Username and Password not accepted.. I tried to allow "less secure apps" and desactivate 2FA. I also tried to generate an app specific password. Same error.
I don't understand what is going on.
EDIT :
When i printed ENV["USERNAME"] i didn't have what i wrote in my .env file. I had instead my first name, i don't know why. So i changed my .env file to MAIL_USERNAME (instead of USERNAME) and now it's working in development, but unfortunately i get an error 500 in production, and i have no idea how to debug this.
EDIT 2 :
Problem solved ! I just had to add my .env variables in heroku
Gmail used to allow simply passing your valid email and password via a Rails app in order to send emails. But they killed that functionality off, and require that you configure an App Specific Password for this purpose:
https://support.google.com/accounts/answer/185833?hl=en
I think the change came in 2018 or so, I remember that our Rails app was humming along just fine and suddenly it stopped sending messages. At that time, it wasn't widely announced by Gmail that they had made this change, if announced at all, which caught us off guard.
Create your app specific password and use those credentials. See if that starts sending emails for you. Your code looks fine.
I've never been able to successfully use a Yahoo account with a Rails app by the way.

An SMTP To address is required to send a message/Argument Errror

ArgumentError at /contacts
An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.
Good Day Guys,I am having trouble debugging this myself and have consumed so much time I needed your help and explanation as to how why it didn't work.
Things I did already:
1.Added gem 'binding_of_caller'
2.bundle install
goal:
Is when a visitor submit a contact form it supposed to send me a email message automatically.
My woes/confusion:
1.How do you set your email in secrets.yml or put your email wherein you configured the contact form request directly to your email
2.What I did is put
to:myemail.com > secrets.yml both in production and development
3.Am I right?
Please explain this to me as I am going in depth on ruby on rails.
You need to generate a mailer first.
rails g mailer example_mailer
app/mailers/example_mailer.rb This file will be generated by this line.
Then you need to create a method in your mailer where u can define whom to send mail. you can give direct email id or you can take it from database. As in my given example u need to pass user to this method and it will send email to that user's email.
def sample_email(user)
#user = user
mail(to: #user.email, subject: 'Sample Email')
end
Create a HTML template for how your mail will look
app/views/example_mailer/sample_email.html.erb
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Hi <%= #user.name %></h1>
<p>
Sample mail sent using smtp.
</p>
</body>
</html>
Then you need to configure your smtp in /config/environments/production.rb or /config/environments/development.rb whichever environment you are using.
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => 'username#gmail.com',
:password => 'Gmail password',
:authentication => "plain",
:enable_starttls_auto => true
}
Then you need to trigger your mail action any any method from where you are sending mails.
ExampleMailer.sample_email(#user).deliver

Trying to send email with Gmail STP (Rails)

I'm trying to send some emails from my web application. Here is my configuration:
//config/environments/development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'domain.com',
user_name: 'myusername',
password: 'mypassword',
authentication: 'plain',
enable_starttls_auto: true }
// mailers/contact_mailer
class ContactMailer < ApplicationMailer
default from: 'from#gmail.com'
def send_email()
mail(to: 'to#gmail.com', subject: 'Welcome to My Awesome Site')
end
end
// views/contact_mailer/send_email.html.erb
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to example.com, name</h1>
<p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>
So to test it, I ran this command from the Rails command:
ContactMailer.send_email
And I'm getting this result:
irb(main):003:0> ContactMailer.send_email
Rendered contact_mailer/send_email.html.erb within layouts/mailer (0.1ms)
ContactMailer#send_email: processed outbound mail in 10.4ms
=> #<Mail::Message:69980432504260, Multipart: false, Headers: <From: adib.elaraki#gmail.com>, <To: adib.amine.mdr#gmail.com>, <Subject: Welcome to My Awesome Site>, <Mime-Version: 1.0>, <Content-Type: text/html>>
irb(main):004:0>
Unfortunately, after checking my email, I don't receive the email
mail only generates a mailer object. You need to append something like deliver_now for it to actually send. For example:
ContactMailer.send_email.deliver_now

Can a rails application send emails from the local host?

I think I've set up ActionMailer successfully, however emails do not arrive in their inbox, despite the server stating differently:
Sent mail to julian#designimperial.com (2003ms)
Date: Fri, 30 Aug 2013 22:26:41 +0100
From: from#example.com
To: julian#gmail.com
Message-ID: <52210e11bedc9_16501d84f64257a#Julian-PC.mail>
Subject: Welcome to my awesome site!
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to example.com, Julian</h1>
<p>
You have successfully signed up to example.com,
your username is: gogo.<br/>
</p>
<p>
To login to the site, just follow this link: http://example.com/login.
</p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>
Do I need to upload my rails application to a server or heroku inorder for emails to be sent? I know this is the case with PHP mailing and MAMP/XAMPP
Having incorrect settings can result in email failing to send without raising any exceptions. Assuming you're using the SMTP protocol to deliver main, you should ensure that you've properly setup your ActionMailer configuration. Here's a basic configuration for utilizing Gmail (via the Rails Guides):
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: '<username>',
password: '<password>',
authentication: 'plain',
enable_starttls_auto: true }
Enabling delivery errors regarding the action mailer to be raised is absurdly helpful in getting the action mailer working. It's also disabled by default.
To get it working, open your development environment file, located at:
yourappname/config/environments/development.rb
around line 17, there is a method that enables and disables error reporting by taking a boolean:
config.action_mailer.raise_delivery_errors = false
Change it to 'true', and restart the rails server. You now have excellent error reporting from rails.
I also like to put my smtp settings directly below in the same file like this:
#SMTP settings
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
user_name: "mrexample",
password: "01password02"
}
Remember to put your smtp settins in your production.rb and test.rb environment configuration files as well. This example hash is also 100% correct if you're using gmail as the sender address of the emails. The only strings you need to change are the password and username.
Another thing that isn't glaringly obvious with gmail is that your username is everything to left of the # symbol, and the domain everything to the right of the #.
e.g
mrexample#gmail.com
==
config.action_mailer.smtp_settings = {
# address: "smtp.gmail.com",
# port: 587,
domain: "gmail.com",
user_name: "mrexample",
# password: "01password02"
}
Finally, if you're getting the error message
"Errno::ECONNREFUSED (No connection could be made because the target machine actively refused it. - connect(2))"
Chances are the only thing wrong with your application is your smtp settings. Probably your password.

Rails + SendGrid Unauthenticated senders not allowed

I'm currently working on sending emails via sendgrid and currently sending emails to new users is working. ...But strangely, very similar emailing options aren't working - the full email including the recipient is displayed in the log but is never received.
Here's what I have:
In a mail.rb file in initializers:
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => configatron.sendgrid.username,
:password => configatron.sendgrid.password,
:domain => 'heroku.com'
}
ActionMailer::Base.delivery_method = :smtp
with the username and password being defined elsewhere - they are confirmed to have their correct values
When a new user registers, I call my UserMailer class and do the following:
def welcome_email(user)
#email = user.email
#name = user.full_name
mail(to: #email, subject: "Welcome!")
end
And the worker calls it by simply doing the following:
UserMailer.welcome_email(user).deliver
This much works; I receive the email and that's that.
But when I try to send an email from a different method, magically things break down.
In the SAME UserMailer class:
def request(org, recipient, item)
#org = org
#recipient = recipient
#item = item
mail(to: #org.email, subject: "A new request has been posted!")
end
Using the SAME function (although this time outside of a worker so I can debug easily):
UserMailer.request(org, recipient, item).deliver
The email appears in the terminal perfectly:
Sent mail to mypersonalemail#test.com (4717ms)
Date: Mon, 31 Dec 2012 01:03:35 -0800
From: mysendingemail#test.com
To: mypersonalemail#test.com
Message-ID: <[longhexstring]#localhost.localdomain.mail>
Subject: A new request has been posted!
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_50e154e769903_3c41bba7ec576d5";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_50e154e769903_3c41bba7ec576d5
Date: Mon, 31 Dec 2012 01:03:35 -0800
Mime-Version: 1.0
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <[longhex]#localhost.localdomain.mail>
Hello world!
----==_mimepart_50e154e769903_3c41bba7ec576d5
Date: Mon, 31 Dec 2012 01:03:35 -0800
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <[longhex]#localhost.localdomain.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<p>
Hello world!
</p>
</body>
</html>
But, I check my inbox on my personal email, the junk, the trash, and received nothing. Even sendgrid has no logs of me ever requesting to send request emails! But the welcome emails are working perfectly fine, and even are logged through sendgrid. I don't see what could cause one group of emails to send but not another and this is really baffling. No obvious errors in syntax jump out at me, and the values I use are of the correct datatype and not nil.
Any help with this strange issue would be extremely appreciated.
The solution ended up being remarkably simple, so for those who find this thread and need help I'll at least post what I did.
In development.rb I did the following to see the error being raised:
config.action_mailer.raise_delivery_errors = true
And got this message:
Net::SMTPFatalError - 550 Cannot receive from specified address <mypersonalemail#test.com>: Unauthenticated senders not allowed
Which is strange considering I thought I was authenticated with the info I put into .env Outputting my configatron.sendgrid.username sure enough is nil. Still trying to figure out why that would be and I'm still not sure how the welcome emails were sent.
Sure enough, changing my smtp settings to be hardcoded values for authentication worked like a charm. Now the question becomes how to get the ENV to not come out nil...
The end solution was simply me being on the wrong localhost. I was using rails's default rails server at port 3000, but foreman start (not sure if by default but in my project's case) was using port 5000 instead.
I had this issue when running code via rake. The problem was that the SENDGRID_USERNAME and SENDGRID_PASSWORD environment variables stored in my .env were not loaded automatically via rake. The solution was to run rake through foreman:
foreman run bundle exec rake namespace:task

Resources