duangang4940 2016-05-30 10:53
浏览 212

使用golang中的gmail API发送带有附件的电子邮件

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

  • 写回答

1条回答 默认 最新

  • doujia2021 2017-12-15 18:27
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧