-
-
Notifications
You must be signed in to change notification settings - Fork 84
SMIME Signing Example
Winni Neessen edited this page Jan 9, 2025
·
2 revisions
This example shows how to enable S/MIME signing in go-mail.
Test on play.go.dev
package main
import (
"crypto/tls"
"log"
"os"
"github.com/wneessen/go-mail"
)
func main() {
// Load the TLS certificate from the certificate and key file
keypair, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Fatalf("failed to load keypair: %s", err)
}
message := mail.NewMsg()
if err = message.From("[email protected]"); err != nil {
log.Fatalf("failed to set FROM address: %s", err)
}
if err = message.To("[email protected]"); err != nil {
log.Fatalf("failed to set TO address: %s", err)
}
message.Subject("This is my first test mail with go-mail!")
message.SetBodyString(mail.TypeTextPlain, "This will be the content of the mail.")
// Initialize the S/MIME signing
if err = message.SignWithTLSCertificate(&keypair); err != nil {
log.Fatalf("failed to sign message: %s", err)
}
// Deliver the mails via SMTP
client, err := mail.NewClient(os.Getenv("SMTP_HOST"),
mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithTLSPortPolicy(mail.TLSMandatory),
mail.WithUsername(os.Getenv("SMTP_USER")), mail.WithPassword(os.Getenv("SMTP_PASS")),
)
if err != nil {
log.Fatalf("failed to create new mail delivery client: %s", err)
}
if err := client.DialAndSend(message); err != nil {
log.Fatalf("failed to deliver mail: %s", err)
}
log.Printf("Test mail successfully delivered.")
}Most of the code is explained in the Simple-Mailer-Example. Check out that page for detailed explanations.
The main differences to the Simple Mailer Example are, that we load our TLS certificate from a
X.509 RSA private-/public keypair in the first few lines of code. Later, when our message is composed,
we initialize the S/MIME signing using the Msg.SignWithTLSCertifcate
method and provide our imported keypair as parameter. This makes sure, once the mail is rendered during the
delivery process, that the mail is S/MIME signed before it's sent out.
Socials: go-mail on Mastodon | #go-mail on Discord | #go-mail on Slack