Ruby Sending Email - SMTP

SMTP (Simple Mail Transfer Protocol) is a set of rules for transmitting mail from a source address to a destination address, and it controls how messages are relayed.

Ruby provides Net::SMTP to send email, and provides two methods: new and start:

newThe method has two parameters:

  • server nameDefaults to localhost
  • port numberDefaults to 25

startThe method has the following parameters:

  • server- SMTP server IP, defaults to localhost
  • port- Port number, defaults to 25
  • domain- Sender domain, defaults to ENV["HOSTNAME"]
  • account- Username, defaults to nil
  • password- User password, defaults to nil
  • authtype- Authentication type, defaults tocram_md5

The SMTP object instance method invokes sendmail, with the following parameters:

  • source- A string, an array, or anything returned by each iterator at any given time.
  • sender- A string that appears in the email's form field.
  • recipients- A string or an array of strings representing the recipient's address.

Example

The following provides a simple Ruby script to send email:

Example

require 'net/smtp' message = <<MESSAGE_END From: Private Person <me@fromdomain.com> To: A Test User <test@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com' end
In the above example, you have set up a basic email message. Note the correct header format. An email needs From, To, and Subject, and there needs to be a blank line between the text content and the header information.

Use Net::SMTP to connect to the SMTP server on the local machine, and use the send_message method to send the email. The method parameters are the sender's email and the recipient's email.

If you don't have an SMTP server running on your local machine, you can use Net::SMTP to communicate with a remote SMTP server. If you use webmail services (such as Hotmail or Yahoo Mail), your email provider will provide you with the details of the outgoing mail server:

Net::SMTP.start('mail.your-domain.com')

The above code will connect to the mail server with host mail.your-domain.com and port 25. If you need to fill in a username and password, the code is as follows:

Net::SMTP.start('mail.your-domain.com', 25, 'localhost', 'username', 'password', :plain)

The above example uses the specified username and password to connect to the mail server with host mail.your-domain.com and port 25.


Sending HTML Email with Ruby

Net::SMTP also provides support for sending emails in HTML format.

When sending an email, you can set the MIME version, document type, and character set to send an email in HTML format.

Example

The following example is used to send an email in HTML format:

Example

require 'net/smtp' message = <<MESSAGE_END From: Private Person <me@fromdomain.com> To: A Test User <test@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com' end

Sending Email with Attachments

If you need to send an email with mixed content, you need to set Content-type to multipart/mixed. This way you can add attachment content to the email.

Before transmission, the attachment needs to use thepack("m")function to convert its content into base64 format.

Example

The following example will send an email with attachment /tmp/test.txt:

Example

require 'net/smtp' filename = "/tmp/test.txt" #Read the file and encode it in base64 format filecontent = File.read(filename) encodedcontent = [filecontent].pack("m") # base64 marker = "AUNIQUEMARKER" body =<<EOF This is a test email to send an attachement. EOF #Define the main header information part1 =<<EOF From: Private Person <me@fromdomain.net> To: A Test User <test@todmain.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=#{marker} --#{marker} EOF # Define message action part2 =<<EOF Content-Type: text/plain Content-Transfer-Encoding:8bit #{body} --#{marker} EOF #Define the attachment part part3 =<<EOF Content-Type: multipart/mixed; name=\"#{filename}\"Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename="#{filename}" #{encodedcontent} --#{marker}-- EOF mailtext = part1 + part2 + part3 # Send email begin Net::SMTP.start('localhost') do |smtp| smtp.sendmail(mailtext, 'me@fromdomain.net', ['test@todmain.com']) end rescue Exception => e print "Exception occured: " + e end

Note:You can specify multiple recipient addresses, but they need to be separated by commas.

Other Extensions