Sent emails with Action Mailer - ruby

I am trying to send an email to example#gmail.com with Action Mailer (Ruby on Rails). The method sendactivation is correctly executed and the message "Email sent" is displayed. However, I never receive any email. Actually, the output "Test" is never printed. My webapp is hosted on Heroku Cedar-10.
class UsersController < ApplicationController
def sendactivation
UserMailer.welcome_email()
render :json => {
:result => "Email sent"
}
end
end
end
class UserMailer < ActionMailer::Base
def welcome_email()
mail(to: "example#gmail.com",
body: "Hello",
content_type: "text/html",
subject: "Already rendered!")
puts "Test"
end
end
This is the configuration I have on my config/environment/production.rb. Actually I wanted to send it with Office 365 but I suppose it is easier to debug with a Gmail account.
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: 'example#gmail.com',
password: '########',
authentication: 'plain',
enable_starttls_auto: true }
What am I doing wrong? Is there anything I need to change on my Gmail configuration?
ANSWER: In addition to the marked answer, I needed to set the "from" address in the welcome_email method.

Call method deliver:
UserMailer.welcome_email.deliver

UserMailer.welcome_email.deliver_now
From the Rails Guide: See section 2.1.4
class SendWeeklySummary
  def run
    User.find_each do |user|
      UserMailer.weekly_summary(user).deliver_now
    end
  end
end

Related

How use sessions with Whats app cloud api?

Need to build chat bot with whatsapp, so i use Whats app cloud api + Sinatrarb.
When i need to send the session its sends perfectually, but its doesnt work
class WhatsAppSender < Sinatra::Base
configure :development do
register Sinatra::Reloader
enable :sessions
set :session_secret, "secret"
set :session_store, Rack::Session::Pool
end
configure do
enable :sessions
set :session_secret, "secret"
set :session_store, Rack::Session::Pool
end
post '/bot' do
request.body.rewind
body = JSON.parse request.body.read
# puts body
puts session[:answer]
if body['entry'][0]['changes'][0]['value'].include?("messages")
user_text = body['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
case
when user_text == "hi"
# puts session[:answer]
response = HTTP.auth("Bearer mytoken")
.headers(:accept => "application/json")
.post("https://graph.facebook.com/v14.0/myid/messages",
:json => { messaging_product: "whatsapp",
recipient_type: "individual",
to: "mynumber",
type: "text",
some_text: "some text",
text: { preview_url:
false,
body: "hi man"}
})
session[:answer] = "booking_amount"
puts response
when session[:answer] == "booking_amount"
puts "session works"
when user_text.downcase == "d"
session.clear
puts "cleared"
end
end
end
end
then i inspect request, sinatra session works fine, set the cookie
Set-Cookie rack.session=BAh7CEkiD3Nlc3Npb25faWQGOgZFVG86HVJhY2s6OlNlc3Npb246OlNlc3Npb25JZAY6D0BwdWJsaWNfaWRJIkViNThiYmJjMjdmYjI4MGU0ZTMxMDY4NzE4MDllOWVhYTBlNTVlM2UwMjg4ZWE3OWRiMjVmYTlkNThmZjczNzI3BjsARkkiCWNzcmYGOwBGSSIxbEJydTFnUm5tSTVCOVZUT1pZelNwSFY3a3ZUNGxiVmVHS2FlZVFvYVJsOD0GOwBGSSINdHJhY2tpbmcGOwBGewZJIhRIVFRQX1VTRVJfQUdFTlQGOwBUSSItNDJiNzI3MTFjNTdmZDA5YTk1MjY0NmY0N2Q0YWJjMjk0ODk5OTZhMQY7AEY%3D--f88a49537f00d65faf60da839b05d847d47f288d; path=/; HttpOnly
But its doesn't work... Maybe i should use another language or framework? please help.

Rails 5.2 ActionMailer Mail won't send. Can't see any error in server

Trying to send a volunteering form through SMTP using Gmail, Sendgrid or anything really however I have Action Mailer all set up and I presume I should really be seeing the email come through when I look at the email. I can see this error below but cannot see any error or receive any email at all. I've tried writing puts in my create action but I do not see those either so this is hopefully an easy fix as I'm missing something or have something not follow the usual Rails convention.
I'm using rails 5.2
What I see in the server:
Started GET "/volunteer?utf8=%E2%9C%93&authenticity_token=AZ%2FAflVf%2BlqRUYm45Jo82wAMpq%2B%2BY%2F93piLbeRXdK5n%2FQIWhuaUL3Oe2%2FSwzR%2FCLvj%2FAKW%2BBgD8dPd8vJYRDBA%3D%3D&volunteer_message%5Bname%5D=test+name&volunteer_message%5Bemail%5D=email%40test.com&volunteer_message%5Bphone_number%5D=88888888&volunteer_message%5Bbody%5D=test+email&commit=Send" for 127.0.0.1 at 2018-10-10 17:29:42 +0100
Processing by PagesController#volunteer as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"AZ/AflVf+lqRUYm45Jo82wAMpq++Y/93piLbeRXdK5n/QIWhuaUL3Oe2/SwzR/CLvj/AKW+BgD8dPd8vJYRDBA==", "volunteer_message"=>{"name"=>"test name", "email"=>"email#test.com", "phone_number"=>"88888888", "body"=>"test email"}, "commit"=>"Send"}
Ok so here's my code and the way it's all layed out.
PagesController.rb contains a page called volunteer and this contains the partial (Called _new.html.erb) which is the form which is in it's own folder called volunteer_messages
views/volunteer_messages/_new.html.erb
<%= simple_form_for #volunteer_message, url: create_volunteer_message_url do |f| %>
<%= #volunteer_message.errors.full_messages.join(', ') %>
<%= f.input :name, placeholder: 'name' %>
<%= f.input :email, placeholder: 'email' %>
<%= f.input :phone_number, placeholder: 'phone number' %>
<%= f.input :body, placeholder: 'body' %>
<%= f.submit 'Send' %>
<% end %>
routes created
# is this causing a problem do you think?
get '/volunteer' => 'pages#volunteer'
# volunteer message routes
get '/volunteer', to: 'volunteer_message#new', as: 'new_volunteer_message'
post '/volunteer', to: 'volunteer_message#create', as: 'create_volunteer_message'
models/volunteer_message.rb
class VolunteerMessage
include ActiveModel::Model
attr_accessor :name, :email, :phone_number, :body
# validates :name, :email, :phone_number, :body, presence: true
end
mailers/volunteer_message_mailer.rb
class VolunteerMessageMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.volunteer_message_mailer.volunteer.subject
#
def volunteer(volunteer_message)
#body = volunteer_message.body
#subject = "Volunteer Request sent from www.myapp.com"
mail to: "myemail#example.com", from: volunteer_message.email
end
end
volunteer_messages_controller.rb
class VolunteerMessagesController < ApplicationController
def new
#volunteer_message = VolunteerMessage.new
end
def create
#volunteer_message = VolunteerMessage.new volunteer_message_params
if #volunteer_message.valid?
VolunteerMessageMailer.volunteer(#volunteer_message).deliver_now
redirect_to new_volunteer_message_url
flash.now[:notice] = "We have received your volunteer request and will be in touch soon!"
else
flash.now[:notice] = "There was an error sending your volunteer request. Please try again."
render :new
end
end
private
def volunteer_message_params
params.require(:volunteer_message).permit(:name, :email, :phone_number, :body)
end
end
pages_controller.rb
class PagesController < ApplicationController
def volunteer
#lead = Lead.new
#volunteer_message = VolunteerMessage.new
end
end
development.rb
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
enable_starttls_auto: true,
user_name: 'me#gmail.com',
password: 'gmailapppassword',
authentication: 'plain'
}
Not sure what else I can add here. I do not think I even need he stmp_settings to see action mailer actually show the template of the email being sent?
Also I'm guessing it is somehting to do with the form and the route because ive added puts messages into the create action on the volunteer_message controller and do not see them in my server log.
I'm not getting any errors when pressing submit. I do notice the params going into the url but that's it. it stays there and when refreshes stays on the same screen.
example:
http://localhost:3000/volunteer?utf8=%E2%9C%93&authenticity_token=AZ%2FAflVf%2BlqRUYm45Jo82wAMpq%2B%2BY%2F93piLbeRXdK5n%2FQIWhuaUL3Oe2%2FSwzR%2FCLvj%2FAKW%2BBgD8dPd8vJYRDBA%3D%3D&volunteer_message%5Bname%5D=test+name&volunteer_message%5Bemail%5D=email%40test.com&volunteer_message%5Bphone_number%5D=88888888&volunteer_message%5Bbody%5D=test+email&commit=Send
Is the clue in the server text in the image that shows params going to the pages controller. I do not really want that. Just want the partial to be there but the action to work of the create action in the volunteer_messages controller.
Any help be much appreciated. Thanks.

How could I pass parameter to this block

I want to send an email every day with a different attachment. So I think I should pass the parameter to mail's initialize block. I read some articles about ruby block but I can not find the right way to implement it. How could I do it the right way and why does the mail's initialize method pass a block? Thank you.
require 'mail'
class MailSender
attr_accessor :created_at
def initialize
delivery_options = {
address: 'xxmail.com',
port: 25,
user_name: 'xxx#xxmail.com',
password: 'xxxxxx',
authentication: :login
}
Mail.defaults do
delivery_method :smtp, delivery_options
end
self.created_at = DateTime.now.prev_day.strftime("%F")
end
def notify
mail = Mail.new do
from 'xxx#xxmail.com'
to 'xxx#xxmail.com'
subject 'mailtest'
body 'The first mail.'
add_file :filename => "#{created_at}.txt", :content => File.read("#{created_at}.txt")
end
mail.deliver!
end
end

ActionMailer isn't sending my email

I'm trying to use ActionMailer to automatically send a user an email. However, after save of the user, which should trigger the email. I don't see that any message has been sent to my inbox. The save took place without mistakes, but the mail never arrived. What is the problem?
mailers
class OrderNotifier < ActionMailer::Base
default from: "from#example.com"
def received(order)
#order = order
mail to: order, subject: 'Pragmatic Store Order Confirmation'
end
end
development.rb
Depot::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
config.action_mailer.delivery_method = :sendmail
config.action_mailer.delivery_method = :test
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address:
"smtp.gmail.com",
port:
587,
domain:
"domain.of.sender.net",
authentication: "plain",
user_name:
"dave",
password:
"secret",
enable_starttls_auto: true
}
end
controller.rb
def create
#order = "a2010#mail.ru"
...
respond_to do |format|
if #user.save
OrderNotifier.received(#order).deliver
format.html { redirect_to #user}
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
...
end
view/order_notifier
Welcome to example.com
Thank you for your recent order from The Pragmatic Store.
you should only have one of those settings:
config.action_mailer.delivery_method = :sendmail
config.action_mailer.delivery_method = :test
config.action_mailer.delivery_method = :smtp
other than that always have the log/development.log file open and see what happens. rails will most likely tell you what it's about to do.
if you want to learn more about debugging, read this http://nofail.de/2013/10/debugging-rails-applications-in-development/

Action Mailer - Rails 4

I am playing around with action mailer, and I don't understand a couple of things
class MYMailer < ActionMailer::Base
default from: "bar#gmail.com"
....
end
in my production.rb file:
#config.action_mailer.default_url_options = { :host => 'www.example.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 111,
domain: 'gmail.com',
user_name: 'foo#gmail.com',
password: 'foobar',
authentication: 'plain',
enable_starttls_auto: true }
1) First of all what is this default from: "bar#gmail.com" ?
The from value is read from my production file, and I receive emails from foo#gmail.com. So what is the point of default from: "bar#gmail.com"
2) Second what is the point of #config.action_mailer.default_url_options = { :host => 'www.example.com' } ? I read something on the official guides but I didn't get it. My app still sends email without it..
Thanks
1) Gmail Api Do not support sent email from different adress(protect from spam/spoof)
2) Rails can send email from self application and this options tell him what host use.

Resources