Search code examples
gomailgun

Send byte slice in inline attachment with Mailgun


I'm using the Mailgun package for Go and would like to send an inline image using cid. In my html template for mailgun I have the correct cid:qr-code.png set up. However I have to add an inline attachment to my email with the qr code. I use the this method to generate a QR code:

code, err := qrcode.Encode(data, qrcode.Medium, 256) // code is a []byte

Now I need to add this code to my email as an inline attachment with the cid property set to qr-code.png

The message.AddBufferAttachment("qr-code.png", code) correctly attaches the image, but does not inline it because I can't set the cid property.

Now I know this is possible with mailgun because the following code in .js can accomplish it using mailgun.

mg.Attachment({
  data: base64Buffer,
  filename: "qr-code.png",
  cid: "cid:qr-code.png",
}),

I just can't seem to do it with the go Mailgun package. Note: I can't write the image to a file and on the os and then attach it.


Solution

  • You can use the the AddReaderInline function

    message.AddReaderInline(filename, readCloser)

    Since you need to convert []bytes to io.ReadCloser you can convert to io.Reader then to io.ReadCloser

    ioutil.NopCloser(bytes.NewReader(code))