Attachments - With Mail Helper Class
package main
import (
"fmt"
"log"
"os"
"encoding/base64"
"io/ioutil"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
func main () {
// create new *SGMailV3
m := mail .NewV3Mail ()
from := mail .NewEmail ("test" , "[email protected] " )
content := mail .NewContent ("text/html" , "<p>Sending different attachments.</p>" )
to := mail .NewEmail ("Example User" , "[email protected] " )
m .SetFrom (from )
m .AddContent (content )
// create new *Personalization
personalization := mail .NewPersonalization ()
personalization .AddTos (to )
personalization .Subject = "Attachments - Demystified!"
// add `personalization` to `m`
m .AddPersonalizations (personalization )
// read/attach .txt file
a_txt := mail .NewAttachment ()
dat , err := ioutil .ReadFile ("testing.txt" )
if err != nil {
fmt .Println (err )
}
encoded := base64 .StdEncoding .EncodeToString ([]byte (dat ))
a_txt .SetContent (encoded )
a_txt .SetType ("text/plain" )
a_txt .SetFilename ("testing.txt" )
a_txt .SetDisposition ("attachment" )
// read/attach .pdf file
a_pdf := mail .NewAttachment ()
dat , err = ioutil .ReadFile ("testing.pdf" )
if err != nil {
fmt .Println (err )
}
encoded = base64 .StdEncoding .EncodeToString ([]byte (dat ))
a_pdf .SetContent (encoded )
a_pdf .SetType ("application/pdf" )
a_pdf .SetFilename ("testing.pdf" )
a_pdf .SetDisposition ("attachment" )
// read/attach inline .jpg file
a_jpg := mail .NewAttachment ()
dat , err = ioutil .ReadFile ("testing.jpg" )
if err != nil {
fmt .Println (err )
}
encoded = base64 .StdEncoding .EncodeToString ([]byte (dat ))
a_jpg .SetContent (encoded )
a_jpg .SetType ("image/jpeg" )
a_jpg .SetFilename ("testing.jpg" )
a_jpg .SetDisposition ("inline" )
a_jpg .SetContentID ("Test Attachment" )
// add `a_txt`, `a_pdf` and `a_jpg` to `m`
m .AddAttachment (a_txt )
m .AddAttachment (a_pdf )
m .AddAttachment (a_jpg )
request := sendgrid .GetRequest (os .Getenv ("SENDGRID_API_KEY" ), "/v3/mail/send" , "https://api.sendgrid.com" )
request .Method = "POST"
request .Body = mail .GetRequestBody (m )
response , err := sendgrid .API (request )
if err != nil {
log .Println (err )
} else {
fmt .Println (response .StatusCode )
fmt .Println (response .Body )
fmt .Println (response .Headers )
}
}