7

我在 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

4

4 回答 4

17

您需要将From邮件字段设置为Sandy Sender <sender@example.com>

...
From: Sandy Sender <sender@example.com>
To: recipient@example.com
Subject: Hello!

This is the body of the message.

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

或者,您可以使用我的包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)
    }
}
于 2014-12-02T15:33:40.767 回答
1

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

于 2021-09-16T12:23:16.517 回答
0

您可以检查类似的项目是否jpoehls/gophermail效果更好。

它有一个像这样的测试用例:

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

它在内部(main.go)调用应该遵循RFC 5322SetMailAddress()的方法。mail.ParseAddress()

于 2014-12-02T12:12:42.500 回答
0

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

func (a *Address) String() string

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

我写了例子:

go_smtp.go

于 2014-12-02T12:17:57.150 回答