How to send emails in Golang

How to send emails in golang with the standard Go library and gomail library using Gmail

Pranav Sharma
Pranav Sharma
August 23, 2021
3 min read

The Email API by developers, for developers

Integrate in minutes with our Email API or SMTP and deliver emails to customer's inbox instantly. Mailazy Email API built for developers that fits into any tech stack.

How to send emails in Golang

Introduction

net/smtp is a built-in go package and implements SMTP protocol. It provides a simple way for sending mail through smtp servers. We will explore the inbuilt net/smtp package and Gomail package to send out the emails.

Prerequisites

  • Basic understanding of Golang
  • Go version 1.10 or higher.

Send an Email with net/smtp

Importing packages
package main

import (
    "fmt"
    "net/smtp"
)
Sending the email
package main

import (
    "fmt"
    "net/smtp"
    "os"
)

// Main function
func  main() {
    // from is sender's email address
    from := os.Getenv("MAIL")
    password := os.Getenv("PASSWD")

    // toList is a list of email addresses that email is to be sent
    toList := []string{"example@gmail.com"}

    // host is address of server that the  sender's email address belongs,
    // in this case it's gmail.
    host := "smtp.gmail.com"

    // It's the default port of smtp server
    port := "587"

    // This is the message to send in the mail
    msg := "Hello World!"

    // We can't send strings directly in mail,
    // strings need to be converted into slice bytes
    body := []byte(msg)

    // PlainAuth uses the given username and password to
    // authenticate to host and act as identity.
    auth := smtp.PlainAuth("", from, password, host)

    // SendMail uses TLS connection to send the mail
    // The email is sent to all address in the toList,
    // the body should be of type bytes, not strings
    // This returns an error if any occurred.
    err := smtp.SendMail(host+":"+port, auth, from, toList, body)

    // handling the errors
    if err != nil { 
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Println("Successfully sent email!")
}

Send an Email with Gomail

Importing package
package main

import (
    "crypto/tls"
    "fmt"
    gomail "gopkg.in/mail.v2"
)
Sending the email
package main

import (
    "crypto/tls"
    "fmt"
    gomail "gopkg.in/mail.v2"
)

func main() {
    m := gomail.NewMessage()

    m.SetHeader("From", "youremail@gmail.com")
    m.SetHeader("To", "recipient@example.com")

    m.SetHeader("Subject", "Sending Email with Goalang")

    // Set the email body. You can set plain text or html with text/html
    m.SetBody("text/plain", "Hello World!")

    // Settings for SMTP server
    d := gomail.NewDialer("smtp.gmail.com", 587, "youremail@gmail.com", "yourpassword")

    // This is only needed when the SSL/TLS certificate is not valid on the server.
    // In production this should be set to false.
    d.TLSConfig = &tls.Config{InsecureSkipVerify: true}

    if err := d.DialAndSend(m); err != nil {
        fmt.Println(err)
        panic(err)
    }

    return
}

Common Issues and Resolutions

  • Error: Invalid login: 535-5.7.8 Username and Password not accepted.
    A potential solution to this error could be to enable the Gmail service to use it in third-party apps. To resolve this error just login in Gmail account and enable less secure apps using this link https://myaccount.google.com/lesssecureapps
  • ETIMEDOUT errors
    Check your firewall settings. Timeout usually occurs when you try to open a connection to a port that is firewalled either on the server or on your machine.
  • TLS errors
    Check your antivirus settings. Antiviruses often mess around with email port usage. Node.js might not recognize the MITM cert your antivirus is using.
    Latest Node versions allow only TLS versions 1.2 and higher, some servers might still use TLS 1.1 or lower. Check Node.js docs how to get correct TLS support for your app.

Conclusion

Gmail either works well or it does not work at all. It is probably easier to switch to an alternative email service provider such as Mailazy instead of fixing issues with Gmail. Using gmail for your production server isn’t recommended either, you should opt for an email provider to manage your emails.
Configuring and setting up Mailazy is easy and seamless and emails can be sent in a few minutes!



Mailazy Docs

Integrate with Transactional email service in minutes

click here

Most Popular Tags

EngineeringSMTPShort ReadBest PracticesEmailAPIsEmail SecurityCommunicationEmail APIEmail Delivery



What is Mailazy?

Mailazy is a Transactional Email Platform specially built for developers which satisfies the requirement for use cases like Reset Password Emails, OTP Emails, Welcome Emails, and so on. The Mailazy platform helps you to send transactional emails seamlessly and track email deliverability. Mailazy enables your applications to send messages via a simple HTTP REST interface or via easy SMTP integration and abstracts away the complexities of sending transactional emails.

Visit website

Pranav Sharma

Pranav Sharma

Pranav Sharma is a Lead Software Development Engineer at Mailazy. He graduated in Computer Science and considers himself a learner of life. He loves to play cricket, football and computer games.

View Profile