emailgoemail-attachmentsgomail

How to send an attachment from memory using gomail?


I want to send a CSV attachment without saving the attached data to a hard drive first. I'm using gomail throughout my code. How can I attach data directly from memory using gomail?


Solution

  • You can use the FileSetting functions that gomail provides

    csv, _ := gocsv.MarshalBytes(someData) // ignoring the error for the example
    
    email := gomail.NewMessage()
    email.Attach(
        fmt.Sprintf("Filename.csv"),
        gomail.SetCopyFunc(func(w io.Writer) error {
            _, err := w.Write(csv)
            return err
        }),
        gomail.SetHeader(map[string][]string{"Content-Type": {"text/csv"}}),
    )