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
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:
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:
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
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
Note:You can specify multiple recipient addresses, but they need to be separated by commas.
Other Extensions