首页 > 解决方案 > sinatra 中的小马邮件

问题描述

如何使用 Pony gem 将邮件发送到我的 gmail.com 地址。

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

我尝试了这里描述的那个,但它不起作用。

Pony.mail(
  :name => params[:name],
  :mail => params[:mail],
  :body => params[:body],
  :to => 'a_lumbee@gmail.com',
  :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'
})

标签: rubysinatrapony

解决方案


重要的是,您必须配置您的 gmail 帐户:激活 2 因素授权并设置应用程序密码。这有点搜索,但并不复杂。

我已经这样配置了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            => 'blablablab@gmail.com',
         :password             => '', #application password generated by google in clear
         :authentication       => :plain, 
         :domain               => 'lafindumois.fr' # the HELO domain provided by the client to the server
    }
end

用法:

if @user.save
        @valide_url = request.base_url + '/vali/'+@user.token
        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

推荐阅读