How to send email in golang?

Member

wiley

by wiley , in category: Golang , 16 days ago

How to send email in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by emely , 16 days ago

@wiley You can send email via smtp server and you can use net/smtp package in golang, here is my simple code example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
   "fmt"
   "net/smtp"
)

func sendEmail(from string, password string, to []string, message string) error {
   // smtp server configuration.
   smtpHost := "smtp.gmail.com"
   smtpPort := "587"

   // Authentication.
   auth := smtp.PlainAuth("", from, password, smtpHost)

   // Sending email.
   err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, []byte(message))

   return err
}

func main() {

   err := sendEmail("from_email@gmail.com", "email_password", []string{"sender@example.com"}, "Test email")

   if err != nil {
      fmt.Println("Error happened: " + err.Error())
   }
}