【问题标题】:Sending emails with "Name" <email> from Go从 Go 发送带有“名称”<email> 的电子邮件
【发布时间】:2016-07-28 21:44:39
【问题描述】:

我正在使用net/smtp 发送电子邮件,它似乎无法处理电子邮件中的联系人姓名。

c, _ := smtp.Dial("smtp.example.com:25")
c.Mail(`jdoe@example.com`)

而不是

c, _ := smtp.Dial("smtp.example.com:25")
c.Mail(`"John Q. Doe" <jdoe@example.com>`)

有没有好的方法来处理这个问题?如果可以的话,我更喜欢封装和标准的东西,但如果可以做到的话,我愿意使用原始 SMTP。

【问题讨论】:

    标签: email go smtp standard-library


    【解决方案1】:

    你能不加双引号试试吗?即

    c.Mail(`John Q. Doe <jdoe@example.com>`)
    

    【讨论】:

    • 不起作用。如果您查看golang.org/src/net/smtp/smtp.go#L233,您会发现他们已经在包装它,所以Mail 根本无法处理这个问题。
    • 看起来你是对的,你不能用标准库做到这一点,但我认为他们试图只强制完全符合规范的代码。不过复制和修改 smtp.go 看起来并不难。
    【解决方案2】:
    smtpServer := "smtp.example.com"
    auth := smtp.PlainAuth("", "from@example.com", "******", smtpServer)
    
    from := mail.Address{"fromName", "from@example.com"}
    to := mail.Address{"toName", "to@example.com"}
    msg := []byte("From: " + from.String() + "\r\n" +
    "To: " + to.String() + "\r\n" +
    "Subject: Awesome Subject !\r\n" +
    "This is the email body.\r\n")
    err := smtp.SendMail(smtpServer + ":25", auth, from.Address,[]string{to.Address}, msg)
    if err != nil {
        log.Fatal(err)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多