How to Send Emails in Go Using the Net/SMTP Package

You might often need to send emails to many accounts using programs for authentication and many other purposes.

The SMTP protocol defines standards that allow email communication across mail servers and mail transfer agents, while the IMAP protocol is for receiving emails.

4

Go provides functionality for email-related activities defined by the RFC in the net/smtp package, which also contains 8BITMIME, AUTH, and STARTTLS extensions.

The code used in this project is available in aGitHub Repositoryand is free for you to use under the MIT license.

Photo of a message emoji on a wall

The net/smtp package is part of the Go standard library, so you don’t need to install any external package. You only need to import the package before using it.

You will also need to import thelogpackage to log errors to the console and thecrypto/tlspackage to configure a safe connection.

Yahoo mail generate password user interace

Once you’ve imported the net/smtp package, you should write aSendMail()function to send the mail and then call the function in the main function.

TheSendMail()function would contain the code that sends the mail to recipients.

Proof that the email was sent successfully

How Sending Emails Work

The SMTP protocol defines the parameters that every mail needs to have. These parameters are the sender and receiver mail addresses, a port on which the mail is sent, a host server, and a message.

The parameters stated above are important for sending emails.

A diagram showing four components connecting to a central database server

In this tutorial, you’ll learn to send Yahoo emails. However, the process is the same for whatever Mail Server Provider (MSP) you use.

Since you’re using Yahoo Mail, log in to yourYahoo Mailaccount, head on toAccount Info,and click theAccount Securitytab. Then generate an app password. You’ll need to name the app, and then Yahoo Mail will create a password for the app, and you can use the password in your code along with your mail address.

In theSendMail()function, you’ll declare three variables; a variable that holds the string of your email, one that holds your email password, and a string that holds the email address you are sending messages to.

You can use a slice andloop through the elementsif you intend to send them to multiple recipients.

Getting and Setting the Email Host and Port

The SMTP protocol uses the host and port numbers to identify the email source. This is where your MSP comes in. You need to know the host and port number your MSP allows you to use.

Check this resource for a list of MSP hosts andport numbersif you use public emails like Gmail, Yahoo, or Outlook. Google has turned off “less secure apps” for Gmail; you might want to secure your application if you’re using Gmail.

Once you’ve got the port number and host address, assign them to variables like this:

The host and port numbers above are from Yahoo Mail for use on regular accounts. The server is hosted at smtp.mail.yahoo.com, and you’re allowed to use port465to send Emails.

Declaring the Contents of the Email

The next step is to declare the contents of the mail as variables. The subject and the body make up the message.

Thesubjectvariable is the subject of the email; thebodyvariable is the body of the email you’re sending.

Setting the Email Headers

You’ll need to make a map of strings to denote the headers of the email.

First, you create a map of string keys and values and set the headers of your address, the recipient’s address, and the subject, as shown above. Using a range for-loop on theheadersmap, amessagevariable is declared to contain the headers and the message using string formatting.

Authenticating the Email

The email needs authentication to verify the source. The smtp package provides functionality for email authentication using thePlainAuth.ThePlainAuthmethod takes in the identity, sender’s Email, password, and host as parameters and returns anAuthobject you’ll use to send the email.

The identity is your username, which can be left blank, as seen in this case.

Creating a Connection for the Email

Some mail service providers require you to send the email via a connection. In this article, we’ll be making aTCP connectionto the server with TLS configurations.

In the code above, you made a TLS configuration by referencing theConfigstruct whereInsecureSkipVerifywas set totrue, and the server name was assigned to thehostvariable.

You must create a TCP connection using theDialmethod of thetlspackage. Thedialmethod takes in the connection type (TCP), in this case, the server address and the TLS connection configurations.

In the code above, you made a TCP connection and handled errors; you’ll have instantiated a new smtp package using theNewClientmethod of thenet/smtppackage. TheNewClientmethod takes in a connection and host, respectively.

Now that you’ve created ansmtpclient instance, you have to set the parameters of thesmtpClientand handle errors.

In the example above, you passed the authentication, sender address, and recipient address parameters to their respective methods and handled errors.

Finally, you have to write to the connection instance, and you’re able to do that by creating a writer using theDatamethod of yoursmtp clientinstance.

After creating a writer, you write a byte slice of the message using theWritemethod as in the example above.

Close the writer and quit the smtp client connection instance using the above code. TheSendMail()function returns a success message, as shown above.

On calling theSendMail()function in themainfunction, you should get the success message logged to your console, and the email` sent to your recipient.

There’s More to the Net Package

The net package contains many packages for network-related functionalities and the smtp package is just one of them. it’s possible to also use the TCP and HTTP packages for networking-related development.

You might find the net/smtp package overwhelming if you’re not a backend developer. There are many other alternatives for sending emails quickly with fewer lines of code. You can check out email marketing companies like SendGrid, Twilio, and MailChimp and newsletter services like Substack and Revue that allow you to send emails to many users without stress.

With a simple database abstraction package, using SQL from Go is easier than you might think.

Sometimes the smallest cleaning habit makes the biggest mess.

Who asked for these upgrades?

The key is not to spook your friends with over-the-top shenanigans.

My iPhone does it all, but I still need my dumb phone.

Tor spoiled me forever.

Technology Explained

PC & Mobile