Ruby Send Mail - SMATP
Simplified Mail Transfer Protocol (SMTP) is a set of rules for transferring mail from source address to destination address, which controls the way the mail is transferred.
Ruby provides Net::SMTP to send mail and provides two methods new and start:The
new method has two parameters:
- server name defaults to localhost
- port number defaults to 25
The start method has the following parameters:
- server - SMTP server IP, default is localhost
- port - port number, default is 25
- domain - the sender's domain name, default is ENV["HOSTNAME"]
- account - username, default is nil
- password - User password, default is nil
- authtype - Authentication type, default cram_md5
The SMTP object instantiation method calls sendmail with the following parameters:
- source - Any string or array or anything returned by each iterator at any time.
- sender - A string that appears in the form field of email.
- recipients - An array of strings or strings representing the address of the recipient.
A simple Ruby script is provided below to send mail:
Use Net::SMTP to connect to the SMTP server on the local machine, use the send_message method to send mail, the method parameters are sender mail and recipient mail.
If you don't have an SMTP server running on this machine, you can use Net::SMTP to communicate with a remote SMTP server. If you use a webmail service (such as Hotmail or Yahoo Mail), your email provider will provide you with the details of the sending mail server:
The above code will connect to the mail server with mail.your-domain.com and port number 25. If you need to fill in the username and password, the code is as follows:
The above example uses the specified username and password to connect to the mail server with the host number of mail.your-domain.com and port number 25.
Send HTML mail using Ruby
Net::SMTP also provides support for sending HTML-formatted messages.
When sending an email, you can set the MIME version, document type, and character set to send HTML-formatted messages.
The following example is used to send an HTML-formatted message:
Send an email with attachments
If you need to send an email with mixed content, you need to set the Content-type to multipart/mixed. This will add attachment content to the message.
Attachments need to use the pack("m") function to convert their content to base64 format before transfer.
The following example will send an email with the attachment /tmp/test.txt:
Note: You can determine numerous delivers to send, however separate them with commas.