SendGrid SMTP 电子邮件未发送到 Go 中的抄送和密件抄送地址

SendGrid SMTP emails are not delivered to CC and BCC addresses in Go

我正在尝试使用抄送和密件抄送发送电子邮件。电子邮件不会发送到 CC 和 BCC 地址。但是抄送地址会显示给收件人的详细信息。截图如下。

我正在使用 golang net/smtpSendGrid。我的代码示例如下。

func SendEmail() error {

        email := entity.Email{
        From:    "info@somewhere.cloud",
        To:      []string{"crajuceveifre-5717@yopmail.com"},
        ReplyTo: "dileulobugre-7335@yopmail.com",
        Subject: "Email Subject",
        Body:    "Email Body",
        BCC:     []string{"lecrecezufeu-9078@yopmail.com"},
        CC:      []string{"houcroissezitri-3721@yopmail.com"},
    }
    emailMessageBytes := ToBytes(email)

    smtpAuth := smtp.PlainAuth("", "apikey", config.Config.EmailClientApiKey, config.Config.EmailClientHost)

    err := smtp.SendMail(config.Config.EmailClientHost+":"+config.Config.EmailClientPort, smtpAuth, email.From, email.To, emailMessageBytes)

    if err != nil {
        log.Printf("smtp error: %s", err)
        return err
    }

    return nil
}

func ToBytes(m entity.Email) []byte {
    buf := bytes.NewBuffer(nil)

    buf.WriteString(fmt.Sprintf("From: %s\r\n", m.From))
    buf.WriteString(fmt.Sprintf("To: %s\r\n", strings.Join(m.To, ",")))
    buf.WriteString(fmt.Sprintf("Reply-To: %s\r\n", m.ReplyTo))
    if len(m.CC) > 0 {
        buf.WriteString(fmt.Sprintf("Cc: %s\r\n", strings.Join(m.CC, ",")))
    }

    if len(m.BCC) > 0 {
        buf.WriteString(fmt.Sprintf("Bcc: %s\r\n", strings.Join(m.BCC, ",")))
    }
    buf.WriteString(fmt.Sprintf("Subject: %s\r\n", m.Subject))

    buf.WriteString("MIME-Version: 1.0\n")
    writer := multipart.NewWriter(buf)
    boundary := writer.Boundary()

    buf.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\n\n", boundary))
    buf.WriteString(fmt.Sprintf("--%s\n", boundary))

    buf.WriteString("Content-Type: text/html; charset=utf-8\n")
    buf.WriteString(m.Body)
    buf.WriteString(fmt.Sprintf("\n\n--%s\n", boundary))

    return buf.Bytes()
}

请帮帮我。提前致谢:)

在幕后,smtp.SendMail 为每个 to 收件人调用 smtp.Client.Rcptto 切片指示谁将实际收到电子邮件。电子邮件正文中的收件人纯粹是信息性的 - 事实上,他们甚至不需要匹配真实的收件人信息。

因此,要解决您的地址问题,您需要收集所有 toccbcc 收件人:

var all []string
for _, a := range [][]string{email.To, email.CC, email.BCC} {
    all = append(all, a)
}

err := smtp.SendMail(
    config.Config.EmailClientHost+":"+config.Config.EmailClientPort,
    smtpAuth,
    email.From,
    all, //email.To,
    emailMessageBytes,
)

另外,由于每个收件人都会收到电子邮件的正文,bcc 用户应该 列在 正文,出于明显的隐私原因。

所以删除这个:

// if len(m.BCC) > 0 {
//    buf.WriteString(fmt.Sprintf("Bcc: %s\r\n", strings.Join(m.BCC, ",")))
//}