Ruby has the ability to send emails directly using SMTP (simple mail transfer protocol). This post will show you how to configure the inbuilt library to send email with ruby SMTP.

What is SMTP?

SMTP is a protocol that was developed to allow computers to send electronic mail to one another. The protocol is widely supported and included in Ruby with the package. For SMTP to work you need to communicate with an SMTP server that is set up to handle emails for a particular email domain (such as @gmail.com).

Import NET/SMTP

Sending email with SMTP in Ruby is easy. In a new ruby file add:

Then to send an email start a process and perform sending inside the do block:

Notice the host and port given. This is the SMTP server that we wish to email. You must know the SMTP server location of the email provider you wish to contact. Typically, this can be found by running on a domain for records. For an @gmail account for instance the MailServer can be found running on port 465 of the host . You can use ruby to send email with SMTP to gmail accounts by using the host and port with .

Testing a MailServer with TELNET

To test that an SMTP server is functioning on the desired port and host use to call a server:

If the server is working you should see a response like so:

Using your own SMTP server

If you have an email host like Gmail or MailSlurp you can use the SMTP server host they provide to connect to a server and send emails. For MailSlurp you can use the function to get access credentials:

Testing SMTP servers with Ruby and RSpec

Use ruby to send SMTP emails and use RSpec and MailSlurp to test your processes. MailSlurp gives you unlimited disposable mailboxes that you can connect to with SMTP in ruby. You can then use the MailSlurp API or Ruby SDK to wait for emails to arrive and validate their contents. Here is a full example:

Further reading

For more tips on sending email with Ruby see the MailSlurp Ruby email library.