4
votes

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'\r\n" +
    "reply-to: [email protected]\r\n" +
    "To:  " + msg.To + "\r\n" +
    "Subject: " + msg.Subject + "\r\n" +
    "\r\n" + 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

1
You should try sending the whole message (including attachement, with proper headers) inside message.Raw without using the Media() method. I have had some success with it but did not use the proper headers, so I won't post any working code. - syntagma

1 Answers

0
votes

I were having the same issue, after long time reading find a library that support attachments https://github.com/jordan-wright/email