DEV Community

Yusuf Turhan Papurcu for Golang

Posted on

đź“§ Sending E-Mail from Gmail Using Golang.

First setup your gmail account like this. You can access here from settings/all settings.

Open Forwarding and POP/IMAP. Enable IMAP and save changes.

Then open Google Account/Security. Open Application Passwords. (You need 2-Step Verification)

Select Post and Other device. I named “Golang Emails”. Then create it.

We get the application password. Let’s Code it!

package main

import (
    "log"
    "net/smtp"
)

func main() {
    send("hello bro, This just test.")
}

func send(body string) {
    from := "yusufturhanp@gmail.com"
    pass := "*****"
    to := "tryusuf97@gmail.com"

    msg := "From: " + from + "\n" +
        "To: " + to + "\n" +
        "Subject: Hello there\n\n" +
        body

    err := smtp.SendMail("smtp.gmail.com:587",
        smtp.PlainAuth("", from, pass, "smtp.gmail.com"),
        from, []string{to}, []byte(msg))

    if err != nil {
        log.Printf("smtp error: %s", err)
        return
    }
    log.Println("Successfully sended to " + to)
}
Enter fullscreen mode Exit fullscreen mode

You must change from to sender mail, pass to Application Password and “to” to reciver email. Run and look your sended posts.

We sent the first email. And we set up the google account. You can now send as many emails as you want.

Top comments (0)