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

在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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统
  • ¥15 VB.NET2022如何生成发布成exe文件
  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!