Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

AlexandraMT
AlexandraMT

Posted on

     

Sending Emails with Ruby

Let’s say you have a working Ruby app and need to add an email delivery functionality to it. This could be related to user authentication, or any other kind of transactional emails, it makes no difference. This tutorial is tailored is aimed at helping you implement sending emails with Ruby.

If you want to read the full article, check it out the on the Mailtrap’s blog: Sending Emails with Ruby

Options for sending an email in Ruby

Mostly, you can pick one of the three options.

The simplest one is usingNet::SMTP class. It provides the functionality to send email via SMTP. The drawback of this option is that Net::SMTP lacks functions to compose emails. You can always create them yourself, but this takes time.

The second option is to use a dedicatedRuby gem like Mail, Pony, or others. These solutions let you handle email activities in a simple and effective way. Action Mailer is a perfect email solution through the prism of Rails. And, most likely, this will be your choice.

The third option is classSocket. Mostly, this class allows you to set communication between processes or within a process. So, email sending can be implemented with it as well. However, the truth is that Socket does not provide you with extensive functionalities, and you’re unlikely to want to go with it.

Now, let’s try to send an email using each of the described solutions.

How to send emails in Ruby via Net::SMTP

From our experience, the use of that option in a regular web app is uncommon. However, sending emails via Net::SMTP could be a fit if you usemruby (a lightweight implementation of the Ruby language) on some IoT device. Also, it will do if used in serverless computing, for example,AWS Lambda. Check out this script example first and then we’ll go through it in detail.

require 'net/smtp'message = <<END_OF_MESSAGEFrom: YourRubyApp <info@yourrubyapp.com>To: BestUserEver <your@bestuserever.com>Subject: Any email subject you wantDate: Tue, 02 Jul 2019 15:00:34 +0800Lorem IpsumEND_OF_MESSAGENet::SMTP.start('your.smtp.server', 25) do |smtp|  smtp.send_message message,  'info@yourrubyapp.com',  'your@bestuserever.com'end
Enter fullscreen modeExit fullscreen mode

This is a simple example of sending a textual email via SMTP (official documentation can be foundhere). You can see four headers: From, To, Subject, and Date. Keep in mind that you have to separate them with a blank line from the email body text. Equally important is to connect to the SMTP server.

Net::SMTP.start('your.smtp.server', 25) do |smtp|

Naturally, here will appear your data instead of‘your.smtp.server‘, and 25 is a default port number. If needed, you can specify other details like username, password, or authentication scheme (:plain, :login, and :cram_md5). It may look as follows:

Net::SMTP.start('your.smtp.server', 25, ‘localhost’, ‘username’, ‘password’ :plain) do |smtp|

Here, you will connect to the SMTP server using a username and password in plain text format, and the client’s hostname will be identified as localhost.

After that, you can use thesend_message method and specify the addresses of the sender and the recipient as parameters. The block form of SMTP.start (Net::SMTP.start('your.smtp.server', 25) do |smtp|) closes the SMTP session automatically.

In the Ruby Cookbook, sending emails with the Net::SMTP library is referred to as minimalism since you have to build the email string manually. Nevertheless, it’s not as hopeless as you may think of. Let’s see how you can enhance your email with HTML content and even add an attachment.

Sending an HTML email in Net::SMTP

Check out this script example that refers to the message section.

message = <<END_OF_MESSAGEFrom: YourRubyApp <info@yourrubyapp.com>To: BestUserEver <your@bestuserever.com>MIME-Version: 1.0Content-type: text/htmlSubject: Any email subject you wantDate: Tue, 02 Jul 2019 15:00:34 +0800A bit of plain text.<strong>The beginning of your HTML content.</strong><h1>And some headline, as well.</h1>END_OF_MESSAGE
Enter fullscreen modeExit fullscreen mode

Apart from HTML tags in the message body, we’ve got two additional headers:MIME-Version andContent-type. MIME refers to Multipurpose Internet Mail Extensions. It is an extension to Internet email protocol that allows you to combine different content types in a single message body. The value ofMIME-Version is typically 1.0. It indicates that a message is MIME-formatted.

As for theContent-type header, everything is clear. In our case, we have two types – HTML and plain text. Also, make sure to separate these content types using defining boundaries.

Except for MIME-Version and Content-type, you can use other MIME headers:

  • Content-Disposition – specifies the presentation style (inline or attachment)
  • Content-Transfer-Encoding – indicates a binary-to-text encoding scheme (7bit, quoted-printable, base64, 8bit, or binary).

Sending an email with an attachment in Net::SMTP

Let’s add an attachment, such as a PDF file. In this case, we need to updateContent-type to multipart/mixed. Also, use thepack("m") function to encode the attached file with base64 encoding.

require 'net/smtp'filename = "/tmp/Attachment.pdf"file_content = File.read(filename)encoded_content = [file_content].pack("m")   # base64marker = "AUNIQUEMARKER"
Enter fullscreen modeExit fullscreen mode

After that, you need to define three parts of your email.

Part 1 – Main headers

part1 = <<END_OF_MESSAGEFrom: YourRubyApp <info@yourrubyapp.com>To: BestUserEver <your@bestuserever.com>Subject: Adding attachment to emailMIME-Version: 1.0Content-Type: multipart/mixed; boundary = #{marker}--#{marker}END_OF_MESSAGE
Enter fullscreen modeExit fullscreen mode

Part 2 – Message action

part2 = <<END_OF_MESSAGEContent-Type: text/htmlContent-Transfer-Encoding:8bitA bit of plain text.<strong>The beginning of your HTML content.</strong><h1>And some headline, as well.</h1>--#{marker}END_OF_MESSAGE
Enter fullscreen modeExit fullscreen mode

Part 3 – Attachment

part3 = <<END_OF_MESSAGEContent-Type: multipart/mixed; name = "#{filename}"Content-Transfer-Encoding:base64Content-Disposition: attachment; filename = "#{filename}"#{encoded_content}--#{marker}--END_OF_MESSAGENow, we can put all the parts together and finalize the script. That’s how it will look:require 'net/smtp'filename = "/tmp/Attachment.pdf"file_content = File.read(filename)encoded_content = [file_content].pack("m")   # base64marker = "AUNIQUEMARKER"part1 = <<END_OF_MESSAGEFrom: YourRubyApp <info@yourrubyapp.com>To: BestUserEver <your@bestuserever.com>Subject: Adding attachment to emailMIME-Version: 1.0Content-Type: multipart/mixed; boundary = #{marker}--#{marker}END_OF_MESSAGEpart2 = <<END_OF_MESSAGEContent-Type: text/htmlContent-Transfer-Encoding:8bitA bit of plain text.<strong>The beginning of your HTML content.</strong><h1>And some headline, as well.</h1>--#{marker}END_OF_MESSAGEpart3 = <<END_OF_MESSAGEContent-Type: multipart/mixed; name = "#{filename}"Content-Transfer-Encoding:base64Content-Disposition: attachment; filename = "#{filename}"#{encoded_content}--#{marker}--END_OF_MESSAGEmessage = part1 + part2 + part3begin  Net::SMTP.start('your.smtp.server', 25) do |smtp|    smtp.send_message message,    'info@yourrubyapp.com',    'your@bestuserever.com'  end
Enter fullscreen modeExit fullscreen mode

Can I send an email to multiple recipients in Net::SMTP?

Definitely, you can.send_message expects second and subsequent arguments to contain recipients’ emails. For example, like this:

Net::SMTP.start('your.smtp.server', 25) do |smtp|  smtp.send_message message,  'info@yourrubyapp.com',  'your@bestuserever1.com',  ‘your@bestuserever2.com’,  ‘your@bestuserever3.comend
Enter fullscreen modeExit fullscreen mode

Best Ruby gems for sending emails

In Ruby ecosystem, you can find specific email gems that can improve your email sending experience.

Ruby Mail

This library is aimed at giving a single point of access to manage all email-related activities including sending and receiving email.

Pony

You might have heard a fairy tale about sending an email in one command. Hold on to your hats, cause it’s real and provided byPony gem.

ActionMailer

This is the most popular gem for sending emails on Rails. In case your app is written on top of it, ActionMailer will certainly come up. It lets you send emails using mailer classes and views.

Using Mailtrap to test email sending with Net::SMTP

Setup is very simple. Once you’re in your demo inbox, copy the SMTP credentials on the SMTP Settings tab and insert them in your code. Or you can get a ready-to-use template of a simple message in the Integrations section. Just choose a programming language or framework your app is built with.

require 'net/smtp'message = <<END_OF_MESSAGEFrom: YourRubyApp <info@yourrubyapp.com>To: BestUserEver <your@bestuserever.com>Subject: Any email subject you wantDate: Tue, 02 Jul 2019 15:00:34 +0800Lorem IpsumEND_OF_MESSAGENet::SMTP.start('smtp.mailtrap.io', 587, '<username>', '<password>', :cram_md5) do |smtp|  smtp.send_message message,  'info@yourrubyapp.com',  'your@bestuserever.com'end
Enter fullscreen modeExit fullscreen mode

If everything is alright, you’ll see your message in the Mailtrap Demo inbox. Also, you can try to check your email with HTML content and an attachment. Mailtrap allows you to see how your email will look and check HTML if necessary.

Create aMailtrap account and try to test it on your own for free!

You have just read the full tutorial on how to test and send emails in Ruby. There is still a lot to check out when it comes to Ruby Mail, Pony and Action Mailer. Learn more about Ruby Gems & Socket Class in our fullSending Emails with Ruby articleat Mailtrap.io.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Brand Ambassador at Mailtrap, a product that helps people inspect and debug emails before sending them to real users.
  • Location
    Kyiv
  • Work
    Brand Ambassador at Mailtrap
  • Joined

More fromAlexandraMT

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp