dragon0023
2018-11-17 22:17
浏览 276
已采纳

在gomail v2中发送带有可选附件的电子邮件

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: "example@example.com", To: "some@gmail.com", Subject: "Sub", Body: "B", Filename: "/tmp/image.jpg" })
}

I would like to make Filename as an optional parameter.

for example

    Mail(Params{From: "example@example.com", To: "some@gmail.com", Subject: "Sub", Body: "B" })
}

Thank you

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dru5089 2018-11-18 02:20
    已采纳

    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
    }
    
    打赏 评论

相关推荐 更多相似问题