Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Send email using Go (Golang) via GMail with net/smtp
package main
import (
func main() {
send("hello there")
func send(body string) {
from := ""
pass := "..."
to := ""
msg := "From: " + from + "\n" +
"To: " + to + "\n" +
"Subject: Hello there\n\n" +
err := smtp.SendMail("",
smtp.PlainAuth("", from, pass, ""),
from, []string{to}, []byte(msg))
if err != nil {
log.Printf("smtp error: %s", err)
log.Print("sent, visit")
Copy link

elimisteve commented Jul 5, 2021

@ashishtiwari1993 That worked great for me, thanks!

Copy link

kunal-pahwa commented Nov 11, 2021

can anyone help me to change the display name of the sender i.e if I am sending mail from so I am seeing in the mail list of receiver inbox but I want my custom sender name instead of,
I am using SMTP plain auth

auth := smtp.PlainAuth("", from, password, smtpHost)
smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, body.Bytes())

Copy link

whoiscarlo commented Jul 7, 2022

package main

import (

type loginAuth struct {
  username, password string

func LoginAuth(username, password string) smtp.Auth {
	return &loginAuth{username, password}

func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
	return "LOGIN", []byte{}, nil

func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
	if more {
		switch string(fromServer) {
		case "Username:":
			return []byte(a.username), nil
		case "Password:":
			return []byte(a.password), nil
			return nil, errors.New("Unkown fromServer")
	return nil, nil

func main() {
	// Choose auth method and set it up
	auth := LoginAuth("user","pass")

	// Here we do it all: connect to our server, set up a message and send it
	to := []string{""}
	msg := []byte("To:\r\n" +
		"Subject: New Hack\r\n" +
		"\r\n" +
		"Wonderful solution\r\n")
	err := smtp.SendMail("", auth, "", to, msg)
	if err != nil {

Wonderful hack by

I don't know why Standard library not implementing LOGIN Mechanism.

@ashishtiwari1993 Thank you so much for this! I was going crazy trying to figure it out!!

Copy link

luizuatanabe commented Jul 8, 2022

Enabling "less secure apps" didn't work for me, I kept getting a Error when sending mail: 535 5.7.8 Username and Password not accepted. Learn more at 5.7.8 y19sm6477535pfe.9 - gsmtp even though that was definitely my username and password.

What did was turning turning on 2FA and generating an app password instead. The app password can be used in lieu of your actual gmail password anywhere where your password is required.

Thanks brother, this worked for me (replacing password for app password).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment