How to Send Email via Smtp with Ruby's Mail Gem

How to send email via smtp with Ruby's mail gem?

From http://lindsaar.net/2010/3/15/how_to_use_mail_and_actionmailer_3_with_gmail_smtp

To send out via GMail, you need to configure the Mail::SMTP class to have the correct values, so to try this out, open up IRB and type the following:

require 'mail'

options = { :address => "smtp.gmail.com",
:port => 587,
:domain => 'your.host.name',
:user_name => '<username>',
:password => '<password>',
:authentication => 'plain',
:enable_starttls_auto => true }



Mail.defaults do
delivery_method :smtp, options
end

The last block calls Mail.defaults which allows us to set the global delivery method for all mail objects that get created from now on. Power user tip, you don’t have to use the global method, you can define the delivery_method directly on any individual Mail::Message object and have different delivery agents per email, this is useful if you are building an application that has multiple users with different servers handling their email.

Mail.deliver do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end

Sending mail using mail gem and smtp delivery method rails

As the error says, Missing template user_mailer/conference_result.

You need to create a template app/views/user_mailer/conference_result.html.erb

Ruby and sending emails with Net::SMTP: How to specify email subject?

So I looked at the documentation and it looks like Net::SMTP doesn't support this. In the documentation it says this:

What is This Library NOT?¶ ↑

This library does NOT provide functions to compose internet mails. You must create them by yourself. If you want better mail support, try RubyMail or TMail. You can get both libraries from RAA. (www.ruby-lang.org/en/raa.html)

So I looked into the MailFactory gem (http://mailfactory.rubyforge.org/), which uses Net::SMTP actually:

    require 'net/smtp'
require 'rubygems'
require 'mailfactory'

mail = MailFactory.new()
mail.to = "test@test.com"
mail.from = "sender@sender.com"
mail.subject = "Here are some files for you!"
mail.text = "This is what people with plain text mail readers will see"
mail.html = "A little something <b>special</b> for people with HTML readers"
mail.attach("/etc/fstab")
mail.attach("/some/other/file")

Net::SMTP.start('smtp1.testmailer.com', 25, 'mail.from.domain', fromaddress, password, :cram_md5) { |smtp|
mail.to = toaddress
smtp.send_message(mail.to_s(), fromaddress, toaddress)
}

and now it works!

Ruby gem 'Mail' setting up with SMTP

Try calling mail.deliver!, calling to_s just returns you a string representation of the object.

Alternatively you can call deliver with a block instead of calling new, e.g.

mail = Mail.deliver do
from 'server@company.com'
to 'cvu@company.com'
subject 'This is a test email'
body File.read('test.txt')
end


Related Topics



Leave a reply



Submit