you are better than you think

golang邮件抄送

· Read in about 1 min · (175 Words)
golang smtp to cc bcc

最近接触的一个api模块中使用了smtp.SendMail发送邮件。因为要实现cc功能,看了下源码,简单记录下。

smtp中关于SendMail的声明

SendMail(addr string, a Auth, from string, to []string, msg []byte) error

参数依次是,

    addr: smtp server地址,格式为hostname:port 或者 ip:port;
    a: smtp PlainAuth信息, 包含identity, username, password, host, 即身份id、用户名、密码、smtp服务器host. identify 一般为空,表明identity与username一致;
    from: 发件邮箱
    to: 收件人地址列表,包含to,cc,bcc的所有收件地址
    msg: 邮件内容,包含邮件header和body

来一个栗子

pacakge main

import (
        "fmt"
        "smtp"
        "strings"
        )

func main(){
    from := "from@xxx.com"
    header := make(map[string]string)
    header["From"] = "<I am From>" + from
    header["Subject"] = "send mail with golang"
    header["Content-Type"] = "text/html; charset=UTF-8"
    header["To"] = "a@xxx.com;b@xxx.com"
    header["Cc"] = "cc@xxx.com;"
    header["Bcc"] = "bcc@xxx.com;"

    message:= ""
    content = "<html><body>hello, world!</body></html>"

    auth := smtp.PlainAuth("", "from@gmail.com","password", "xxx.com")

    for k, v := range header {
        message += fmt.Sprintf("%s: %s\r\n", k, v)
    }
    message += "\r\n" + content

    to := []string{}
    tos := strings.Split(header[To],";")
    ccs := strings.Split(header[Cc],";")
    bccs := strings.Split(header[Bcc],";")
    if len(tos) != 0 {
        to = append(to, tos)
    }
    if len(ccs) != 0 {
        to = append(to, ccs)
    }
    if len(bccs) != 0 {
        to = append(to, bccs)
    }

    err:= smtp.SendMail("xxx.com:25", auth, from, to, []byte(message))
    if err !=mil {
        fmt.Println(err)
    }
    fmt.Println("mail sent success")
}
}

Header 中内容只用于在邮件中显示,from 和 Header[«From»]是有区别的,Sendmail中使用的是from. header中的To,Cc,Bcc也是类似,真正to才是收件人。想想邮件组和bcc的实现,还是挺有意思的。

参考资料

  1. https://godoc.org/github.com/emersion/go-sasl
  2. https://tools.ietf.org/html/rfc4616

Comments