How to send mail using .EML file/content in Golang?

624 views
Skip to first unread message

sandip bait

unread,
Sep 13, 2020, 7:06:50 PM9/13/20
to golang-nuts
I am using Standard gomail package for sending mails in Golang. The mail generation part is happing from some other component which i am storing it in a particular location (i.e /path/sample.eml file). And hence , i have pre-cooked mail body in .EML file which i just want process as a new mail. I am able to put/parse the .EML content by using the parsemail package of DusanKasan. There are so many custom headers which i have already set in raw sample.eml file content which i want to send. It will be really helpful if i get an example code saying just pass .eml file as a input so that mail body will generate/render based on .eml file content.

You can fine sample EML content string on .EMLHere is my basic mail sending code using gomail 

package.m := gomail.NewMessage() 
m.SetHeader("From", "al...@example.com") 
m.SetHeader("To", "b...@example.com", "co...@example.com") m.SetAddressHeader("Cc", "d...@example.com", "Dan") 
m.SetHeader("Subject", "Hello!") m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!") m.Attach("/home/Alex/lolcat.jpg") 
 d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") // Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil { panic(err) }

Here is my eml parsing code using parsemail parsemail package

var reader io.Reader // this reads an email message 
email, err := parsemail.Parse(reader) // returns Email struct and error if err != nil { // handle error } fmt.Println(email.Subject) 
fmt.Println(email.From) 
fmt.Println(email.To) 
fmt.Println(email.HTMLBody) 

Thanks & Regards,

Tamás Gulácsi

unread,
Sep 14, 2020, 12:17:42 AM9/14/20
to golang-nuts
Use DialSender returned by gomail.Dial.
You don't need the parsed message for it, just the from and to addresses, and write the contents of the .eml file into the WriterTo as is.

Tamás Gulácsi

unread,
Sep 14, 2020, 6:55:27 AM9/14/20
to golang-nuts
Sth. like
```
var buf bytes.Buffer
buf.Reset()
fh, err := os.Open("path-to-eml")
if err != nil {
  return err
}
_, err = io.Copy(&buf, fh)
fh.Close()
if err != nil {
    return err
}
email, err := parsemail.Parse(bytes.NewReader(buf.Bytes()))

if err != nil { // handle error
  return err
}
d := gomail.NewDialer(...)
sc, err := d.Dial()
if err != nil {
  return err
}
return sc.Send(email.From, []string{email.To}, buf)
```

Or if you don't want to read the whole email into memory (but I think parsemail already does it, unlike the standard net/mail),
you could create a little helper:
```
type copyWriterTo struct { r io.Reader }
func (cw copyWriterTo) WriteTo(w io.Writer) (int64, err) { return io.Copy(w, cw.r) }
```
and use it in `sc.Send`, instead of `buf`.
Reply all
Reply to author
Forward
0 new messages