How to add inline images to HTML emails as MIME attachments in Go?

To add inline images to HTML emails as MIME attachments in Go, you can follow these steps:

  1. Import the required packages:
import ( "encoding/base64" "net/mail" "net/smtp" "path/filepath" "strings" )
  1. Create a function to encode the image file as base64:
func encodeBase64Image(imagePath string) (string, error) { data, err := ioutil.ReadFile(imagePath) if err != nil { return "", err } encoded := base64.StdEncoding.EncodeToString(data) mimetype := mime.TypeByExtension(filepath.Ext(imagePath)) return fmt.Sprintf("data:%s;base64,%s", mimetype, encoded), nil }
  1. Create a function to send the HTML email with inline images:
func sendHTMLEmailWithInlineImages(to, subject, htmlMessage, imagePath string) error { // Get the base64 encoded image inlineImage, err := encodeBase64Image(imagePath) if err != nil { return err } // Create the HTML email multipart message message := mail.NewMultipartMessage("mixed", nil) // Create the HTML part with inline image htmlPart := &mail.InlineHTML{HTML: htmlMessage} htmlPart.AddInline(imagePath, strings.NewReader(inlineImage)) message.AddPart(htmlPart) // Set the email addresses message.SetHeader("From", "[email protected]") message.SetHeader("To", to) // Set the subject message.SetHeader("Subject", subject) // Send the email smtp.SendMail("mailserver:port", nil, "[email protected]", []string{to}, message.Bytes()) return nil }
  1. Call the function with the appropriate parameters:
to := "[email protected]" subject := "Example Subject" htmlMessage := "<html><body><img src=\"cid:example.png\"></body></html>" imagePath := "path/to/example.png" err := sendHTMLEmailWithInlineImages(to, subject, htmlMessage, imagePath) if err != nil { log.Fatal(err) }

Make sure to replace "mailserver:port", "[email protected]", "[email protected]", "Example Subject", "example.png", "path/to/example.png" with the actual values for your email server, sender, recipient, subject, and image file.

Note: This code assumes you're using the built-in net/smtp package for sending emails. You may need to adjust the email sending code if you're using a different SMTP package.

Also, consider error handling and any additional customization you require for your specific email needs.