How to send emails in Golang

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

Kunal Saini
Kunal Saini
August 23, 2021
3 min read

Send Transactional emails With Confidence

Our dedicated support team works around the clock because transactional emails never stop.

Free Sign UpSet up in 2 minutes . No Credit Card Required

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{"[email protected]"}

    // 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", "[email protected]")
    m.SetHeader("To", "[email protected]")

    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, "[email protected]", "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 ReadAPIsBest PracticesEmail SecurityEmailEmail TemplatesGolangMarketing Email



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. Mailazy has built to serve their customers a high value transactional email service. Sending transactional emails shouldn’t be hard with the right transaction email service. With an email service provider or simple transactional email service like Mailazy, you can easily send and track your transactional emails. Our goal is to help you achieve high delivery rates and keep your transactional emails out of the spam folder. We are always there for whenever ypu need us.

Lets get started!

Kunal Saini

Kunal Saini

Kunal 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