Why can't the Mail block see my variable?

前端 未结 3 1672
生来不讨喜
生来不讨喜 2021-02-15 11:35

I\'m new to Ruby and wondering why I am getting an error in this situation using the \'mail\' gem in a simple Sinatra app:

post \"/email/send\" do

  @recipient          


        
3条回答
  •  萌比男神i
    2021-02-15 12:03

    If you'll read through the docs for Mail further you'll find a nice alternate solution that will work. Rather than use:

    Mail.deliver do 
      to @recipient # throws error as this is undefined
      from 'server@domain.com'
      subject 'testing sendmail'
      body 'testing sendmail'
    end
    

    you can use Mail's new() method, passing in parameters, and ignore the block:

    Mail.new(
      to:      @recipient,
      from:    'server@domain.com',
      subject: 'testing sendmail',
      body:    'testing sendmail'
    ).deliver!
    

    or the alternate hash element definitions:

    Mail.new(
      :to      => @recipient,
      :from    => 'server@domain.com',
      :subject => 'testing sendmail',
      :body    => 'testing sendmail'
    ).deliver!
    

    In pry, or irb you'd see:

    pry(main)> Mail.new(
    pry(main)* to: 'me@domain.com',
    pry(main)* from: 'me@' << `hostname`.strip,
    pry(main)* subject: 'test mail gem',
    pry(main)* body: 'this is only a test'
    pry(main)* ).deliver!
    => #, , , >, , , , >
    

    The new method has several variations you can use. This is from the docs also, and might work better:

    As a side note, you can also create a new email through creating a Mail::Message object directly and then passing in values via string, symbol or direct method calls. See Mail::Message for more information.

     mail = Mail.new
     mail.to = 'mikel@test.lindsaar.net'
     mail[:from] = 'bob@test.lindsaar.net'
     mail['subject'] = 'This is an email'
     mail.body = 'This is the body'
    

    followed by mail.deliver!.

    Also note, in the previous example, that there are multiple ways to access the various headers in the message envelope. It's a flexible gem that seems to be well thought out and nicely follows the Ruby way.

提交回复
热议问题