To create and send MIME messages with custom headers in Go, you can use the "mime/multipart" and "net/smtp" packages. Below is an example code snippet:
package main
import (
"bytes"
"fmt"
"net/smtp"
"net/textproto"
)
func main() {
// Set up custom headers
headers := make(textproto.MIMEHeader)
headers.Add("X-Custom-Header", "Value")
// Set up multipart message
multiPart := new(bytes.Buffer)
writer := multipart.NewWriter(multiPart)
part, err := writer.CreatePart(headers)
if err != nil {
fmt.Println("Failed to create MIME part:", err)
return
}
part.Write([]byte("This is the message body"))
// Close the multipart writer
writer.Close()
// Set up SMTP connection
auth := smtp.PlainAuth("", "[email protected]", "your_password", "smtp.example.com")
smtpAddr := "smtp.example.com:587"
// Send the email with custom headers
err = smtp.SendMail(smtpAddr, auth, "[email protected]", []string{"[email protected]"}, multiPart.Bytes())
if err != nil {
fmt.Println("Failed to send email:", err)
return
}
fmt.Println("Email sent successfully")
}
In the above code, we first create a textproto.MIMEHeader
to hold the custom headers. We add the custom header X-Custom-Header
with value Value
.
We then create a multipart.Writer
and call its CreatePart
method passing in the custom headers. We write the message body content to the created part.
After closing the writer, we set up the SMTP connection using smtp.PlainAuth
with your email credentials and the SMTP server details. The SendMail
function is then used to send the email, specifying the sender and recipient email addresses. The message content is passed as multiPart.Bytes()
.
If the email is sent successfully, it prints "Email sent successfully".