7

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Kiril
  • 6,009
  • 13
  • 57
  • 77

4 Answers4

18

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)
    }
}
Ale
  • 1,914
  • 17
  • 25
  • So with go I can send multiple emails via one smtp connection? –  May 05 '15 at 11:17
  • You can with Gomail v2 (still unstable): https://github.com/go-gomail/gomail/issues/10#issuecomment-122090752 – Ale Jul 16 '15 at 21:12
  • @codingrogue Gomail v2 is now out and supports sending multiple emails with a single SMTP connection. Have a look at the Newsletter example: https://godoc.org/gopkg.in/gomail.v2#example-package--Newsletter – Ale Sep 02 '15 at 12:22
1

You can add "From: EmailName<" + EmailAdderss + "> \r\n" to mail header to show whatever EmailName you want, and add Email Address to void duplicate mail.

0

You can check if a project like jpoehls/gophermail works better.

It has a test case like this one:

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

It internally (main.go) calls in SetMailAddress() the method mail.ParseAddress() which is supposed to follow RFC 5322.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

I think you can use mail.Address and use Address.String function formats the address

func (a *Address) String() string

String formats the address as a valid RFC 5322 address. If the address's name contains non-ASCII characters the name will be rendered according to RFC 2047.

and I write example:

go_smtp.go

lidashuang
  • 1,975
  • 4
  • 20
  • 22