This tutorial focuses on teaching you how to use Ruby language to email using the Net::SMTP class.
How to Send a Simple Email
Before we can send an email using SMTP lib, we need to import it. You can do this by adding the required clause as:
Once we have SMTP imported, we need to open a connection to the SMTP server. To do this, we will use the ::start method. This method takes an address as the SMTP server address and the second argument a value as the port for the SMTP protocol.
The ::start will automatically close the connection once it completes.
# open connection
Net::SMTP.start('localhost', 25) do |smtp|
# ..
end
The next step is to compose the message, which has the following components:
- From – This defines the name and address from which to send the email.
- To – This sets the recipient’s address.
- Subject – Subject of the Message
- Date – Date
- Message-Id – Unique message ID
The header components are the first part of the email string. Next, separate them with a new line and add the body of the message.
Finally, close it with the END_OF_MESSAGE block.
Consider the example shown below:
message = << END_OF_MESSAGE
From: Me <address@example.com>
To: You <recipient@address.com>
Subject: Email Subject Goes Here
Date: Wed, 4 Jul 2021 13:37:43 +0300
Message-Id: 28
This is the body of the message
END_OF_MESSAGE
Once we have the message part composed, we can use the send_message method to send the message as shown below:
message = << END_OF_MESSAGE
From: Me <address@example.com>
To: You <recipient@address.com>
Subject: Email Subject Goes Here
Date: Wed, 4 Jul 2021 13:37:43 +0300
Message-Id: 28
This is the body of the message
END_OF_MESSAGE
Net::SMTP.start('localhost', 25) do |smtp|
smtp.send_message message, '[email protected]', '[email protected]'
end
If you need to specify server details, such as username and password, do so in the start method as:
In this example, we specify the client’s hostname, username, password, and authentication method. The methods can be plain, login, etc.
To send the email to multiple users, you can specify the addresses in the send_message method as:
message = << END_OF_MESSAGE
From: Me <address@example.com>
To: You <recipient@address.com>
Subject: Email Subject Goes Here
Date: Wed, 4 Jul 2021 13:37:43 +0300
Message-Id: 28
This is the body of the message
END_OF_MESSAGE
Net::SMTP.start('localhost', 25, 'username', 'password', :login_method) do |smtp|
smtp.send_message message, '[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
end
And with that, you can send a basic email using the Ruby Net::SMTP class.
Conclusion
This short tutorial showed you how to send a basic email using the Ruby Net::SMTP class. Consider the documentation to learn how you can expand on the SMTP class.