GO: Send E-Mail via SMTP mit AUTH

Um eine E-Mail mit GO zu versenden verwende ich das „go-smtp“ Package.

https://github.com/wneessen/go-mail

In diesem Snippet sind 2 Beispiele, einmal für SMTP via SSL und SMTP via TLS.

package main

import (
	"log"
	"github.com/wneessen/go-mail"
)

const (
	MAILSERVER = "mail.server.example.com"
	SMTP_USER  = "go@example.com"
	SMTP_PASS  = "supersecretpassword"
	SENDER     = "go@example.com"
)

func SendMailSSL(tomail string, subject string, msg string) {
	m := mail.NewMsg()
	if err := m.From(SENDER); err != nil {
		log.Fatalf("failed to set From address: %s", err)
	}
	if err := m.To(tomail); err != nil {
		log.Fatalf("failed to set To address: %s", err)
	}
	m.Subject(subject)
	m.SetBodyString(mail.TypeTextPlain, msg)
	c, err := mail.NewClient(MAILSERVER,
		mail.WithPort(465),
		mail.WithSMTPAuth(mail.SMTPAuthPlain),
		mail.WithUsername(SMTP_USER),
		mail.WithPassword(SMTP_PASS),
		mail.WithSSL())
	if err != nil {
		log.Fatalf("failed to create mail client: %s", err)
	}
	if err := c.DialAndSend(m); err != nil {
		log.Fatalf("failed to send mail: %s", err)
	}
}

func SendMailTLS(tomail string, subject string, msg string) {
	m := mail.NewMsg()
	if err := m.From(SENDER); err != nil {
		log.Fatalf("failed to set From address: %s", err)
	}
	if err := m.To(tomail); err != nil {
		log.Fatalf("failed to set To address: %s", err)
	}
	m.Subject(subject)
	m.SetBodyString(mail.TypeTextPlain, msg)
	c, err := mail.NewClient(MAILSERVER,
		mail.WithPort(587),
		mail.WithSMTPAuth(mail.SMTPAuthPlain),
		mail.WithUsername(SMTP_USER),
		mail.WithPassword(SMTP_PASS),
		mail.WithTLSPolicy(mail.TLSMandatory))
	if err != nil {
		log.Fatalf("failed to create mail client: %s", err)
	}
	if err := c.DialAndSend(m); err != nil {
		log.Fatalf("failed to send mail: %s", err)
	}
}

func main() {
	mailbody := `
	Dies ist eine Testmail
	und wir prüfen ob das geht.
	`
	subject := "TESTMAIL"

	SendMailTLS("to@example.com", subject, mailbody)
	SendMailSSL("to@example.com", subject, mailbody)
}

Schreibe einen Kommentar

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.