package models

import (
	"strconv"

	"gopkg.in/gomail.v2"
)

type MyMail struct {
	to     []string
	title  string
	body   string
	attach string
}

func (class *MyMail) To(to string) *MyMail {
	class.attach = ""
	class.to = append(class.to, to)
	return class
}
func (class *MyMail) Title(str string) *MyMail {
	class.title = str
	return class
}
func (class *MyMail) Body(str string) *MyMail {
	class.body = str
	return class
}
func (class *MyMail) Attach(path string) *MyMail {
	class.attach = path
	return class
}
func (class *MyMail) Send() error {
	mailConn := map[string]string{
		"user": "282246101@qq.com",
		"pass": "jwssaevivurwcbai",
		"host": "smtp.qq.com",
		"port": "465",
	}
	port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int

	m := gomail.NewMessage()

	m.SetHeader("From", m.FormatAddress(mailConn["user"], "360xyz"))
	//这种方式可以添加别名，即“XX官方”
	//说明：如果是用网易邮箱账号发送，以下方法别名可以是中文，如果是qq企业邮箱，以下方法用中文别名，会报错，需要用上面此方法转码
	//m.SetHeader("From", "FB Sample"+"<"+mailConn["user"]+">") //这种方式可以添加别名，即“FB Sample”， 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 读者可以自行实验下效果
	//m.SetHeader("From", mailConn["user"])
	m.SetHeader("To", class.to...)      //发送给多个用户
	m.SetHeader("Subject", class.title) //设置邮件主题
	m.SetBody("text/html", class.body)  //设置邮件正文
	if class.attach != "" {
		m.Attach(class.attach) //设置邮件附件
	}
	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])

	err := d.DialAndSend(m)
	return err
}
