emailgosmtpmail-sender

Send e-mail over smtp and change the sender's name


I am sending e-mails over smtp in golang, which works perfectly fine. To set the sender of an e-mail I use the Client.Mail funtion:

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

When the recipient gets the e-mail he sees the sender as plaintext e-mail address: sender@example.com

I want the sender to be displayed like: Sandy Sender <sender@example.com>.

Is this possible? I tried setting the sender to Sandy Sender <sender@example.com> or only Sandy Sender but none of them work. I get the error 501 5.1.7 Invalid address


Solution

  • You need to set the From field of your mail to Sandy Sender <sender@example.com>:

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

    And use the address only (sender@example.com) in Client.Mail.

    Alternatively, you can use my package 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)
        }
    }