Golang Sendmail with Package Gomail


package main

import (
	"crypto/tls"
	"fmt"

	gomail "gopkg.in/mail.v2"
)

  • create function sendmail
func sendMailWithGomail(sender string, receivers string, subject string, content string) error {
	m := gomail.NewMessage()

	// Set E-Mail sender
	m.SetHeader("From", sender)

	// Set E-Mail receivers
	m.SetHeader("To", receivers)

	// Set E-Mail subject
	m.SetHeader("Subject", subject)

	// Set E-Mail body. You can set plain text or html with text/html
	m.SetBody("text/plain", content)

	// Settings for SMTP server
	d := gomail.NewDialer("<host>", "<port>", sender, "<password>")

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

	// Now send E-Mail
	if err := d.DialAndSend(m); err != nil {
		fmt.Println(err.Error())
		return err
	}

	return nil
}

ex. host -> smtp.gmail.com port -> 587 password -> password mail sender

  • call sendmail function
func main() {
	err := sendMailWithGomail(sender, receivers, subject, content)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println("Email Sent Successfully!")

}

package main

import (
	"crypto/tls"
	"fmt"

	gomail "gopkg.in/mail.v2"
)

func sendMailWithGomail(sender string, receivers string, subject string, content string) error {
	m := gomail.NewMessage()

	// Set E-Mail sender
	m.SetHeader("From", sender)

	// Set E-Mail receivers
	m.SetHeader("To", receivers)

	// Set E-Mail subject
	m.SetHeader("Subject", subject)

	// Set E-Mail body. You can set plain text or html with text/html
	m.SetBody("text/plain", content)

	// Settings for SMTP server
	d := gomail.NewDialer("<host>", "<port>", sender, "<password>")

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

	// Now send E-Mail
	if err := d.DialAndSend(m); err != nil {
		fmt.Println(err.Error())
		return err
	}

	return nil
}

func main() {
	err := sendMailWithGomail(sender, receivers, subject, content)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println("Email Sent Successfully!")

}