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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay