DEV Community

Cover image for How to send emails in Golang
Andy Agarwal for Mailazy

Posted on • Originally published at mailazy.com

How to send emails in Golang

How to send emails in Golang

Introduction
net/smtpis 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"
)
Enter fullscreen mode Exit fullscreen mode

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!")
}
Enter fullscreen mode Exit fullscreen mode

Send an Email with Gomail

Importing package

package main

import (
    "crypto/tls"
    "fmt"
    gomail "gopkg.in/mail.v2"
)
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

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!

Top comments (1)

Collapse
 
wneessen profile image
Winni Neessen

gopkg.in/mail.v2 hasn't seen an update in more than 4 years and seems unmaintained. I suggest to use go-mail instead, which is actively developed and maintained.