Pony mail in sinatra

152 Views Asked by At

How can I send mail to my gmail.com address using the Pony gem.

post '/contacts' do 
    @email = params[:email]
    @messages = params[:messages]
end

I tried the one described here, but it doesn't work.

Pony.mail(
  :name => params[:name],
  :mail => params[:mail],
  :body => params[:body],
  :to => '[email protected]',
  :subject => params[:name] + " has contacted you",
  :body => params[:message],
  :port => '587',
  :via => :smtp,
  :via_options => { 
     :address              => 'smtp.gmail.com', 
     :port                 => '587', 
     :enable_starttls_auto => true, 
     :user_name            => 'lumbee', 
     :password             => 'p@55w0rd', 
     :authentication       => :plain, 
     :domain               => 'localhost.localdomain'
})
1

There are 1 best solutions below

0
On

importantly you must configure your gmail account: activate 2 factor authorisation and set an application password. It's a bit of searching, but not complicated.

I have configured like this in app.rb

configure :development do
    # use Pony to send emails. In development, use MailDev
    # run maildev in bash and go to http://localhost:1080
    set :via_options=> {
        :address        => 'localhost',
        :port           => '1025'
    }
end

configure :production do
    set :sessions, :domain => '.www.lafindumois.fr'
    set :via_options => {
         :address              => 'smtp.gmail.com',
         :port                 => '587',
         :enable_starttls_auto => true,
         :user_name            => '[email protected]',
         :password             => '', #application password generated by google in clear
         :authentication       => :plain, 
         :domain               => 'lafindumois.fr' # the HELO domain provided by the client to the server
    }
end

Usage:

if @user.save
        @valide_url = request.base_url + '/vali/'[email protected]
        Pony.mail({
            :to => @user.email,
            :via => :smtp,
            :via_options =>settings.via_options, #settings.via_options is avalable under configure above
            html_body: (erb :"emails/validemail", :layout => false)
        })
        erb :'enregis/enregistree', :layout => :layout_0
        else #irrelevant for this answer
        end #irrelevant for this answer