【问题标题】:Send e-mail over smtp and change the sender's name通过 smtp 发送电子邮件并更改发件人姓名
【发布时间】:2015-01-30 16:07:48
【问题描述】:

我在 golang 中通过 smtp 发送电子邮件,效果很好。要设置电子邮件的发件人,我使用Client.Mail 函数:

func (c *Client) Mail(from string) error

当收件人收到电子邮件时,他将发件人视为明文电子邮件地址:sender@example.com

我希望发件人显示为:Sandy Sender <sender@example.com>

这可能吗?我尝试将发件人设置为Sandy Sender <sender@example.com> 或仅Sandy Sender,但它们都不起作用。我收到错误501 5.1.7 Invalid address

【问题讨论】:

    标签: email go smtp mail-sender


    【解决方案1】:

    您可以检查像jpoehls/gophermail 这样的项目是否效果更好。

    它有一个测试用例like this one:

    m.SetFrom("Domain Sender <sender@domain.com>")
    

    它在内部 (main.go) 调用 SetMailAddress() 方法 mail.ParseAddress()supposed to follow RFC 5322

    【讨论】:

      【解决方案2】:

      我认为您可以使用mail.Address 并使用Address.String 函数格式化地址

      func (a *Address) String() string
      

      字符串将地址格式化为有效的 RFC 5322 地址。如果地址名称包含非 ASCII 字符,则名称将根据 RFC 2047 呈现。

      我写了例子:

      go_smtp.go

      【讨论】:

        【解决方案3】:

        您需要将邮件的From字段设置为Sandy Sender &lt;sender@example.com&gt;

        ...
        From: Sandy Sender <sender@example.com>
        To: recipient@example.com
        Subject: Hello!
        
        This is the body of the message.
        

        并且只使用Client.Mail中的地址(sender@example.com)。

        或者,你可以使用我的包Gomail

        package main
        
        import (
            "gopkg.in/gomail.v2"
        )
        
        func main() {
            m := gomail.NewMessage()
            m.SetAddressHeader("From", "sender@example.com", "Sandy Sender")
            m.SetAddressHeader("To", "recipient@example.com")
            m.SetHeader("Subject", "Hello!")
            m.SetBody("text/plain", "This is the body of the message.")
        
            d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")
        
            if err := d.DialAndSend(m); err != nil {
                panic(err)
            }
        }
        

        【讨论】:

        【解决方案4】:

        您可以在邮件标题中添加"From: EmailName&lt;" + EmailAdderss + "&gt; \r\n" 以显示您想要的任何电子邮件名称,并添加电子邮件地址以使重复邮件无效。

        【讨论】:

        • 另外,与其他答案相比,有点低级......
        • 是的,它只用于 smtp 包。不使用任何其他包。不过还是谢谢
        猜你喜欢
        • 2011-12-13
        • 2012-12-07
        • 2014-01-21
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 2019-01-09
        • 2014-03-25
        相关资源
        最近更新 更多