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

4

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: [email protected]

I want the sender to be displayed like: Sandy Sender <[email protected]>.

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

Friendly answered 2/12, 2014 at 12:1 Comment(0)
S
18

You need to set the From field of your mail to Sandy Sender <[email protected]>:

...
From: Sandy Sender <[email protected]>
To: [email protected]
Subject: Hello!

This is the body of the message.

And use the address only ([email protected]) 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", "[email protected]", "Sandy Sender")
    m.SetAddressHeader("To", "[email protected]")
    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)
    }
}
Steffi answered 2/12, 2014 at 15:33 Comment(3)
So with go I can send multiple emails via one smtp connection?Mak
You can with Gomail v2 (still unstable): github.com/go-gomail/gomail/issues/10#issuecomment-122090752Steffi
@codingrogue Gomail v2 is now out and supports sending multiple emails with a single SMTP connection. Have a look at the Newsletter example: godoc.org/gopkg.in/gomail.v2#example-package--NewsletterSteffi
L
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.

Lavonia answered 16/9, 2021 at 12:23 Comment(2)
Also, a bit low-level, compared to the other answers...Ruthannruthanne
Yeah, It use for smtp package only. Not using any other package. But thanks anywayLavonia
S
0

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

It has a test case like this one:

m.SetFrom("Domain Sender <[email protected]>")

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

Scapolite answered 2/12, 2014 at 12:12 Comment(0)
M
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

Magazine answered 2/12, 2014 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.