Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Originally published atmailazy.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 mainimport (    "fmt"    "net/smtp")
Enter fullscreen modeExit fullscreen mode

Sending the email

package mainimport (    "fmt"    "net/smtp"    "os")// Main functionfunc  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 modeExit fullscreen mode

Send an Email with Gomail

Importing package

package mainimport (    "crypto/tls"    "fmt"    gomail "gopkg.in/mail.v2")
Enter fullscreen modeExit fullscreen mode

Sending the email

package mainimport (    "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 modeExit 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 besent in a few minutes!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
wneessen profile image
Winni Neessen
I work in InfoSec and do open source development in my spare time. Music-lover, Record-collector, Go-Enthusiast, Perl-veteran. Vir potens spiritus.
  • Location
    Cologne, Germany
  • Work
    Director Information Security
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromMailazy

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp