DEV Community

Cover image for Simple email service with GO: Why I stopped using node-mailer
Sebastian Fritsch
Sebastian Fritsch

Posted on

Simple email service with GO: Why I stopped using node-mailer

GO is surprisingly simple when it comes to micro services, not only is GO easy to learn, coding with GO is a lot of fun. It has a built-in formatter and can show you errors right away in the coding lines.

Now let's first see the difference of writing an email service between NodeJS and GO.

Example using node-mailer with NodeJS:

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'youremail@gmail.com',
        pass: 'yourpassword'
    }
});

let mailOptions = {
    from: 'youremail@gmail.com',
    to: 'recipient@example.com',
    subject: 'Node Mailer Test',
    text: 'Hello from Node Mailer!',
    html: '<h1>Hello from Node Mailer!</h1>'
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});
Enter fullscreen mode Exit fullscreen mode

same example using GO from core net package:

package main

import (
    "net/smtp"
)

func main() {
  // Set up authentication information.
  auth := smtp.PlainAuth("", "youremail@gmail.com", 
  "yourpassword", "smtp.gmail.com")

  // Connect to the server, authenticate, and send the email.
  err := smtp.SendMail("smtp.gmail.com:587", auth, 
  "youremail@gmail.com", []string{"recipient@example.com"}, 
  []byte("Subject: Email from Golang\n\nHello from Golang!"))
    if err != nil {
        panic(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Of course they look similar and that doesn't change your mind to switch to a GO mail service except GO is cool!
So the real cool part comes into play when we use templates. With GO we can create .gohtml templates and change the message dynamically with the core html/template package.

Send your first email with go-simple-mail package:
I would suggest to use an app password for gmail authentication: Google app password

package main

import (
    "fmt"
    "github.com/xhit/go-simple-mail/v2"
    "html/template"
    "net/mail"
)

func main() {
    // Set up the email message.
    message := mail.NewMessage()
    message.SetHeader("From", "youremail@gmail.com")
    message.SetHeader("To", "recipient@example.com")
    message.SetHeader("Subject", "Email from Golang")

    // Parse the email body template and execute it with data.
    t, err := template.New("email").Parse(`<!doctype html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title></title>
    </head>

    <body>
    <div>with HTML</div>
        <p>{{.message}}</p>
    </body>
</html>`)
    if err != nil {
        fmt.Println(err)
        return
    }
    data := struct {
        Message string
    }{
        Message: "Hello from Golang!",
    }
    body := new(strings.Builder)
    err = t.ExecuteTemplate(body, "email", data)
    if err != nil {
        fmt.Println(err)
        return
    }
    message.SetBody("text/html", body.String())

    // Set up the SMTP server configuration.
    server := mail.NewSMTPClient()
    server.Host = "smtp.gmail.com"
    server.Port = 587
    server.Username = "youremail@gmail.com"
    server.Password = "yourpassword"
    server.Encryption = mail.EncryptionStartTLS

    // Send the email.
    err = server.Send(message)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Email sent!")
}
Enter fullscreen mode Exit fullscreen mode

checkout more here: GO-simple-mail

Top comments (1)

Collapse
 
cyril_ogoh profile image
ogoh cyril

Hey, nice read, but the main focus that made me come here was the reasons that made you switch. Because if you said it was the templating in HTML, then using Node.js or Golang has no difference.