import ( "bytes" "mime/multipart" ) func main() { // create a new buffer to write the message into var message bytes.Buffer // create a new multipart writer writer := multipart.NewWriter(&message) // create a text part textPart, err := writer.CreateTextPart("body") if err != nil { // handle error } // write the text to the part textPart.Write([]byte("Hello World!")) // close the writer writer.Close() // do something with the message }
import ( "bytes" "mime/multipart" "os" ) func main() { // open the file to attach file, err := os.Open("myFile.txt") if err != nil { // handle error } defer file.Close() // create a new buffer to write the message into var message bytes.Buffer // create a new multipart writer writer := multipart.NewWriter(&message) // create a file part with the name "attachment" and the filename "myFile.txt" filePart, err := writer.CreateFormFile("attachment", "myFile.txt") if err != nil { // handle error } // copy the file contents to the part _, err = io.Copy(filePart, file) if err != nil { // handle error } // close the writer writer.Close() // do something with the message }This example opens a file to attach to the message and then creates a new buffer to write the message into. It then creates a new multipart writer and creates a file part with the name "attachment" and the filename "myFile.txt". It then copies the file contents to the part using the `io.Copy` function. Finally, it closes the writer and the message can be used for something like sending an email. In both examples, the package library used is the `mime/multipart` package.