I have followed https://developers.google.com/gmail/api/quickstart/go. I modified the scope to gmail.MailGoogleComScope and tried sending email. The email gets sent. However, the attachment is not getting sent. It does not give any error as well. Please note the call to Media function is what I tried looking at the code in gmail API, not sure if that is the right way.
When I set the contentType to application/png, the API throws an exception with the message 'png not supported, use message/rfc822'. Following is the code for SendEmail.
func SendEmail(msg EmailMessage) {
ctx := context.Background()
b, err := ioutil.ReadFile("/tmp/client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(ctx, config)
srv, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
var message gmail.Message
temp := []byte("From: 'me'
" +
"reply-to: sender@gmail.com
" +
"To: " + msg.To + "
" +
"Subject: " + msg.Subject + "
" +
"
" + msg.Body)
message.Raw = base64.StdEncoding.EncodeToString(temp)
message.Raw = strings.Replace(message.Raw, "/", "_", -1)
message.Raw = strings.Replace(message.Raw, "+", "-", -1)
message.Raw = strings.Replace(message.Raw, "=", "", -1)
imgFile, err := os.Open("image.png") // a QR code image
if err != nil {
log.Fatalf("Error in opening file")
}
defer imgFile.Close()
mediaOptions := googleapi.ContentType("message/rfc822")
_, err = srv.Users.Messages.Send("me", &message).Media(imgFile, mediaOptions).Do()
if err != nil {
log.Fatalf("Unable to send. %v", err)
}
}
Please suggest what is missing