Monday, November 22, 2021

Sending email using SendGrid in GO


 


In this post we'll send an email using SendGrid in a GO application.


The code is very simple:


import (
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)


message .:= mail.NewV3Mail()
personalization := mail.NewPersonalization()

message.SetFrom(mail.NewEmail("John Doe","from@example.com"))
personalization.AddTos(mail.NewEmail("Alice Bob", "to@example.com"))
personalization.Subject = "My email is here"

body := "This is my <b>HTML</b> body<br>The end!"
message.AddContent(mail.NewContent("text/html", body))
message.AddPersonalizations(personalization)

client := sendgrid.NewSendClient("MY_SECRET_API_KEY_FROM_SENDGRID")
_, err := client.Send(message)
if err != nil {
panic(err)
}
return nil



However, there are some important items to notice:

  • The SendGrid library does not use port 25 to send email. It is based on an HTTPS request to the SendGrid API servers. This is Great for networks with firewall blocking any non HTTP request.
  • You cannot send from any email that you want. To enable sending from a specific email, you need to add a sender, and authenticate it using the SendGrid GUI.
  • The free account in SendGrid is limited to 100 emails per day. In case you want more - you'll need to pay.

Why not just start your own SMTP server, and bypass the 100 emails per day limit?
Well that's because an SMTP server must have an matching MX entry in the DNS server. In addition, many mail servers just block any email arriving from an unknown SMTP server. Some even block the SendGrid SMTP itself.




No comments:

Post a Comment