Email As Micro service in Go lang

Pradip Kharal
2 min readFeb 3, 2021

The micro-services architecture is a development methodology wherein you can divide a single application into a series of smaller services, each executing in its own process and interacting with lightweight mechanisms.

The benefits of email service nowadays are limitless and they are very fast services so in this article we will talk about email service as a micro-service by using go lang.

Now, lets Define Our email template , Email template refers to email body which is send to respective clients. Here we have email template as

template := `<p>Dear, {{full_name}}</p>

<p>&nbsp; &nbsp; {{message}} , Thank You</p>`

Now, lets define object that parse to our template as,

type object struct {

full_name string

message string

}
obj := object{full_name: “Pradip Kharal”, message: “Your Email Works Fine”}

Now, lets define our Template Parser Function ,

func parseTemplate(template string, data object) string {

return strings.NewReplacer(“{{full_name}}”, data.full_name, “{{message}}”, data.message).Replace(template)

}

Everything seems fine so now lets create our new function that send email

func sendEmail(template string, to []string){
from:=“email@email.com”
password:=“do_not_share_your_password”
smtpHost := “smtp.gmail.com”
smtpPort := “587”
message := []byte(template)
auth := smtp.PlainAuth(“”, from, password, smtpHost)
err := smtp.SendMail(smtpHost+”:”+smtpPort, auth, from, to, message)
if err != nil {
fmt.Println(err)
return “Fail”
}
return “Success”
}

Now, Finally lets import required packages and combine all codes,

Congrats! we have done . Now let’s see the result

For Dynamic content we can actually store email template as html text in database and after that when we required that template we just fetch template and use it. One of the database driven email template’s benefits is that even if we are in production and we need to change template, we can change in database and use it rather than use in file based template approach.

That’s all, Thank You……

--

--