Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Golang SMTP Script. Need to add BCC header

Tags:

go

smtp

I am using this well known blank canvas for SMTP in Go.

I need to add in Bcc Blank Carbon Copy address to it but I have tried lots of things and nothing I am trying works which is strange...

I have tried adding in "headers["Bcc"] = "[email protected]" I am sure it is an easy modification.

Thanks in Advance..

package main

import (
   "fmt"
   "log"
   "net"
   "net/mail"
   "net/smtp"
   "crypto/tls"
)

func main() {

from := mail.Address{"", "[email protected]"}
to   := mail.Address{"", "[email protected]"}
subj := "This is the email subject"
body := "This is an example body.\n With two lines."

headers := make(map[string]string)
headers["From"] = from.String()
headers["To"] = to.String()
headers["Subject"] = subj

message := ""
for k,v := range headers {
    message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + body

servername := "smtp.example.tld:465"

host, _, _ := net.SplitHostPort(servername)

auth := smtp.PlainAuth("","[email protected]", "password", host)

tlsconfig := &tls.Config {
    InsecureSkipVerify: true,
    ServerName: host,
}

conn, err := tls.Dial("tcp", servername, tlsconfig)
if err != nil {
    log.Panic(err)
}
c, err := smtp.NewClient(conn, host)
if err != nil {
    log.Panic(err)
}
if err = c.Auth(auth); err != nil {
    log.Panic(err)
}
if err = c.Mail(from.Address); err != nil {
    log.Panic(err)
}
if err = c.Rcpt(to.Address); err != nil {
    log.Panic(err)
}
w, err := c.Data()
if err != nil {
    log.Panic(err)
}
_, err = w.Write([]byte(message))
if err != nil {
    log.Panic(err)
}
err = w.Close()
if err != nil {
    log.Panic(err)
}
c.Quit()
} 
like image 798
Col ᴸᴬᴢᴬᴿᵁᴤ Smith Avatar asked Jan 17 '19 21:01

Col ᴸᴬᴢᴬᴿᵁᴤ Smith


2 Answers

See the following segment from the smtp#SendMail package docs

The msg parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of msg should be CRLF terminated. The msg headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the msg headers.

In other words, don't add them in the headers, just to the recepient list.

In your example boilerplate code, you would add a call to c.Rcpt(...) for each email in the bcc list, and that's it. Nothing to add to headers.

like image 52
user10753492 Avatar answered Oct 18 '22 23:10

user10753492


You need to add a RCPT line for the Bcc address too, for example:

if err = c.Rcpt("[email protected]"); err != nil {
    log.Panic(err)
}
like image 45
lmars Avatar answered Oct 19 '22 00:10

lmars