sending email with optional attachment in gomail v2

1.9k Views Asked by At

I have a package mystuff which deals with sending an email.

package mystuff

import (
    "crypto/tls"
    "gopkg.in/gomail.v2"
)

type Params struct {
    From, To, Subject, Body, Filename string
}

func Mail(p Params) (err error) {
    m := gomail.NewMessage()
    m.SetHeader("From", p.From)
    m.SetHeader("To", p.To)
    m.SetHeader("Subject", p.Subject)
    m.SetBody("text/plain", p.Body)
    m.Attach(p.Filename)

    d := gomail.Dialer{Host: "smtp.example.com", Port: 25}
    d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
    return
}

and the main paskage which sends the email

package main

import . "mystuff"

func main() {
    Mail(Params{From: "[email protected]", To: "[email protected]", Subject: "Sub", Body: "B", Filename: "/tmp/image.jpg" })
}

I would like to make Filename as an optional parameter.

for example

    Mail(Params{From: "[email protected]", To: "[email protected]", Subject: "Sub", Body: "B" })
}

Thank you

2

There are 2 best solutions below

0
Norbert On BEST ANSWER

With filename as optional parameter, you have to check for the length on params filename (string is initialized empty):

func Mail(p Params) (err error) {
    m := gomail.NewMessage()
    m.SetHeader("From", p.From)
    m.SetHeader("To", p.To)
    m.SetHeader("Subject", p.Subject)
    m.SetBody("text/plain", p.Body)
    if len(p.Filename)>0 {
        m.Attach(p.Filename)
    }

    d := gomail.Dialer{Host: "smtp.example.com", Port: 25}
    d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
    return
}
0
Totalys On

You may change Filename parameter to ...string and then you will have more flexibility and the code will be as follows:

type Params struct {
  From, To, Subject, Body string
  Filenames []string
}

Change your Mail func to:

func Mail(p Params) (err error) {
m := gomail.NewMessage()
m.SetHeader("From", p.From)
m.SetHeader("To", p.To)
m.SetHeader("Subject", p.Subject)
m.SetBody("text/plain", p.Body)
for _, f := range p.Filenames {
    m.Attach(f)
}

d := gomail.Dialer{Host: "smtp.example.com", Port: 25}
d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
if err := d.DialAndSend(m); err != nil {
    panic(err)
}
return

}

gomail appends the attachments each time Attach is called.

This way, your code will be more explicity to the user regarding having attachments or not and you will be able to receive more then just one attachment.