### Initialize go-mail Client with Custom NTLM Auth Source: https://github.com/wneessen/go-mail/wiki/NTLM-Auth This example shows how to initialize the go-mail client using the `WithSMTPAuthCustom` option with the previously defined NTLM authentication method. Note the dependency on the 'songxiang93/go-ntlm' package. ```go client, err := mail.NewClient("example.com", mail.WithSMTPAuthCustom(NTLMAuth("user", "password", "domain"))) ``` -------------------------------- ### Install go-mail Package Source: https://github.com/wneessen/go-mail/wiki/Getting-started Use this command to install the latest version of go-mail into your Go project. ```bash go get github.com/wneessen/go-mail ``` -------------------------------- ### Configure go-mail Client for ProtonMail Source: https://github.com/wneessen/go-mail/wiki/Provider-Examples Example for setting up the go-mail Client to send emails via ProtonMail. Requires an SMTP token, which is used as the password for authentication. ```go package main import ( "fmt" "os" "github.com/wneessen/go-mail" ) func main() { username := "your.address@proton.me" password := "" client, err := mail.NewClient("smtp.protonmail.ch", mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithUsername(username), mail.WithPassword(password)) if err != nil { fmt.Printf("failed to create mail client: %s\n", err) os.Exit(1) } message := mail.NewMsg() // Your message-specific code here if err = client.DialAndSend(message); err != nil { fmt.Printf("failed to send mail: %s\n", err) os.Exit(1) } } ``` -------------------------------- ### Send a basic email with go-mail Source: https://github.com/wneessen/go-mail/wiki/Getting-started This example demonstrates how to create, configure, and send a plain text email using go-mail. Ensure you have the go-mail library imported. Replace placeholder credentials and server details with your actual SMTP server information. ```go package main import ( "log" "github.com/wneessen/go-mail" ) func main() { message := mail.NewMsg() if err := message.From("toni.sender@example.com"); err != nil { log.Fatalf("failed to set From address: %s", err) } if err := message.To("tina.recipient@example.com"); err != nil { log.Fatalf("failed to set To address: %s", err) } message.Subject("This is my first mail with go-mail!") message.SetBodyString(mail.TypeTextPlain, "Do you like this mail? I certainly do!") client, err := mail.NewClient("smtp.example.com", mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithUsername("my_username"), mail.WithPassword("extremely_secret_pass")) if err != nil { log.Fatalf("failed to create mail client: %s", err) } if err := client.DialAndSend(message); err != nil { log.Fatalf("failed to send mail: %s", err) } } ``` -------------------------------- ### Configure go-mail Client for Gmail Source: https://github.com/wneessen/go-mail/wiki/Provider-Examples Example for setting up the go-mail Client to send emails via Gmail. Requires an app password if multi-factor authentication is enabled. ```go package main import ( "fmt" "os" "github.com/wneessen/go-mail" ) func main() { username := "your.address@googlemail.com" password := "" client, err := mail.NewClient("smtp.gmail.com", mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithUsername(username), mail.WithPassword(password)) if err != nil { fmt.Printf("failed to create mail client: %s\n", err) os.Exit(1) } message := mail.NewMsg() // Your message-specific code here if err = client.DialAndSend(message); err != nil { fmt.Printf("failed to send mail: %s\n", err) os.Exit(1) } } ``` -------------------------------- ### Configure go-mail Client for iCloud Mail Source: https://github.com/wneessen/go-mail/wiki/Provider-Examples Example for setting up the go-mail Client to send emails via iCloud Mail. Requires an app-specific password for authentication. ```go package main import ( "fmt" "os" "github.com/wneessen/go-mail" ) func main() { username := "your.address@icloud.com" password := "" client, err := mail.NewClient("smtp.mail.me.com", mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithUsername(username), mail.WithPassword(password)) if err != nil { fmt.Printf("failed to create mail client: %s\n", err) os.Exit(1) } message := mail.NewMsg() // Your message-specific code here if err = client.DialAndSend(message); err != nil { fmt.Printf("failed to send mail: %s\n", err) os.Exit(1) } } ``` -------------------------------- ### Create SMTP Client and Send Email Source: https://github.com/wneessen/go-mail/wiki/Getting-started Instantiate an SMTP client with authentication details and send the prepared email message. The DialAndSend method handles connection and delivery. ```go client, err := mail.NewClient("smtp.example.com", mail.WithSMTPAuth(mail.SMTPAuthPlain), mail.WithUsername("my_username"), mail.WithPassword("extremely_secret_pass")) if err != nil { log.Fatalf("failed to create mail client: %s", err) } if err := client.DialAndSend(message); err != nil { log.Fatalf("failed to send mail: %s", err) } ``` -------------------------------- ### Go Bulk Mailer Implementation Source: https://github.com/wneessen/go-mail/wiki/Bulk-Mailer-Example This Go program implements a bulk mailer. It defines a User struct, email templates, and sends personalized emails to a list of users. It uses the go-mail library for email composition and sending, and Go's text/template and html/template packages for dynamic content. Ensure SMTP credentials are set as environment variables (SMTP_USER, SMTP_PASS). ```go package main import ( "fmt" ht "html/template" "log" "math/rand" "os" tt "text/template" "time" "github.com/wneessen/go-mail" ) // User is a simple type allowing us to set a firstname, lastname and mail address type User struct { Firstname string Lastname string EmailAddr string } // Our sender information that will be used in the FROM address field const ( senderName = "ACME Inc." senderAddr = "noreply@acme.com" ) const ( textBodyTemplate = `Hi {{.Firstname}}, we are writing your to let you know that this week we have an amazing offer for you. Using the coupon code "GOMAIL" you will get a 20% discount on all our products in our online shop. Check out our latest offer on https://acme.com and use your discount code today! Your marketing team at ACME Inc.` htmlBodyTemplate = `

Hi {{.Firstname}},

we are writing your to let you know that this week we have an amazing offer for you. Using the coupon code "GOMAIL" you will get a 20% discount on all our products in our online shop.

Check out our latest offer on https://acme.com and use your discount code today!

Your marketing team
  at ACME Inc.

` ) func main() { // Define a list of users we want to mail to userList := []User{ {"Toni", "Tester", "toni.tester@example.com"}, {"Tina", "Tester", "tina.tester@example.com"}, {"John", "Doe", "john.doe@example.com"}, } // Prepare the different templates textTpl, err := tt.New("texttpl").Parse(textBodyTemplate) if err != nil { log.Fatalf("failed to parse text template: %s", err) } htmlTpl, err := ht.New("htmltpl").Parse(htmlBodyTemplate) if err != nil { log.Fatalf("failed to parse text template: %s", err) } var messages []*mail.Msg random := rand.New(rand.NewSource(time.Now().UnixNano())) for _, user := range userList { randNum := random.Int31() message := mail.NewMsg() if err := message.EnvelopeFrom(fmt.Sprintf("noreply+%d@acme.com", randNum)); err != nil { log.Fatalf("failed to set ENVELOPE FROM address: %s", err) } if err := message.FromFormat(senderName, senderAddr); err != nil { log.Fatalf("failed to set formatted FROM address: %s", err) } if err := message.AddToFormat(fmt.Sprintf("%s %s", user.Firstname, user.Lastname), user.EmailAddr); err != nil { log.Fatalf("failed to set formatted TO address: %s", err) } message.SetMessageID() message.SetDate() message.SetBulk() message.Subject(fmt.Sprintf("%s, we have a great offer for you!", user.Firstname)) if err := message.SetBodyTextTemplate(textTpl, user); err != nil { log.Fatalf("failed to add text template to mail body: %s", err) } if err := message.AddAlternativeHTMLTemplate(htmlTpl, user); err != nil { log.Fatalf("failed to add HTML template to mail body: %s", err) } messages = append(messages, message) } // Deliver the mails via SMTP client, err := mail.NewClient("smtp.example.com", mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithUsername(os.Getenv("SMTP_USER")), mail.WithPassword(os.Getenv("SMTP_PASS")), ) if err := client.DialAndSend(messages...); err != nil { log.Fatalf("failed to deliver mail: %s", err) } log.Printf("Bulk mailing successfully delivered.") } ``` -------------------------------- ### Register QQMailQuitErrorHandler with go-mail Client Source: https://github.com/wneessen/go-mail/wiki/Error-Registry Demonstrates how to create a go-mail client for smtp.qq.com and register the custom QQMailQuitErrorHandler to handle specific server responses. ```go client, err := mail.NewClient("smtp.qq.com", mail.WithPort(465), mail.WithSSL()) if err != nil { log.Fatalf("failed to create client: %s\n", err) } qqMailQuitErrorHandler := &QQMailQuitErrorHandler{} client.ErrorHandlerRegistry.RegisterHandler("smtp.qq.com", "QUIT", qqMailQuitErrorHandler) ``` -------------------------------- ### Create a New Email Message Source: https://github.com/wneessen/go-mail/wiki/Getting-started Initialize a new email message and set the sender and recipient addresses. go-mail validates these addresses. ```go package main import ( "log" "github.com/wneessen/go-mail" ) func main() { message := mail.NewMsg() if err := message.From("toni.sender@example.com"); err != nil { log.Fatalf("failed to set From address: %s", err) } if err := message.To("tina.recipient@example.com"); err != nil { log.Fatalf("failed to set To address: %s", err) } } ``` -------------------------------- ### Set Email Subject and Body Source: https://github.com/wneessen/go-mail/wiki/Getting-started Add a subject line and set the plain text content for the email message. ```go message.Subject("This is my first mail with go-mail!") message.SetBodyString(mail.TypeTextPlain, "Do you like this mail? I certainly do!") ``` -------------------------------- ### Send a Basic Email with go-mail Source: https://github.com/wneessen/go-mail/wiki/Simple-Mailer-Example Use this snippet to send a simple plain text email. Ensure you have SMTP credentials and server details configured in your environment or code. ```go package main import ( "log" "os" "github.com/wneessen/go-mail" ) func main() { message := mail.NewMsg() if err := message.From("toni@tester.com"); err != nil { log.Fatalf("failed to set FROM address: %s", err) } if err := message.To("tina@recipient.org"); 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.") // Deliver the mails via SMTP client, err := mail.NewClient("smtp.example.com", 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.") } ``` -------------------------------- ### Enable S/MIME Signing in go-mail Source: https://github.com/wneessen/go-mail/wiki/SMIME-Signing-Example Use this snippet to sign outgoing emails with S/MIME. It requires loading a TLS certificate and key pair before composing and sending the message. Ensure 'cert.pem' and 'key.pem' are available in the execution path. ```go 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("toni@tester.com"); err != nil { log.Fatalf("failed to set FROM address: %s", err) } if err = message.To("tina@tester.com"); 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.") } ``` -------------------------------- ### Custom NTLM SMTP Auth Implementation in Go Source: https://github.com/wneessen/go-mail/wiki/NTLM-Auth This code implements the smtp.Auth interface for NTLM authentication. It requires the 'songxiang93/go-ntlm' package. Ensure the NTLM method is supported by the server before proceeding. ```go import ( "fmt" "github.com/songxiang93/go-ntlm/ntlm" "github.com/wneessen/go-mail/smtp" ) type NTLMCustomAuth struct { UserName string Password string Domain string session ntlm.ClientSession } // Constructor function added by the go-mail team func NTLMAuth(username, password, domain string) smtp.Auth { return &NTLMCustomAuth{ UserName: username, Password: password, Domain: domain, } } func (a *NTLMCustomAuth) Start(info *smtp.ServerInfo) (proto string, toServer []byte, err error) { if len(info.Auth) > 0 { supported := false for _, method := range info.Auth { if method == "NTLM" { supported = true } } if !supported { return "", nil, fmt.Errorf("NTLM auth method not supported") } a.session, err = ntlm.CreateClientSession(ntlm.Version2, ntlm.ConnectionlessMode) if err != nil { return "", nil, fmt.Errorf("failed to create NTLM client session: %v", err) } a.session.SetUserInfo(a.UserName, a.Password, a.Domain) negotiate, err := a.session.GenerateNegotiateMessage() if err != nil { return "", nil, fmt.Errorf("failed to generate negotiate message: %v", err) } return "NTLM", negotiate.Bytes(), nil } return "NTLM", nil, nil } func (a *NTLMCustomAuth) Next(challengeBytes []byte, more bool) (toServer []byte, err error) { if more { challenge, err := ntlm.ParseChallengeMessage(challengeBytes) if err != nil { return nil, fmt.Errorf("failed to parse challenge message: %v", err) } err = a.session.ProcessChallengeMessage(challenge) if err != nil { return nil, fmt.Errorf("failed to process challenge message: %v", err) } authenticate, err := a.session.GenerateAuthenticateMessage() if err != nil { return nil, fmt.Errorf("failed to generate authenticate message: %v", err) } return authenticate.Bytes(), nil } return nil, nil } ``` -------------------------------- ### Go: Send Email via SOCKS5 Proxy Source: https://github.com/wneessen/go-mail/wiki/SOCKS5-Proxy-Example Implement a custom DialContextFunc for go-mail to route SMTP traffic through a SOCKS5 proxy. This requires setting up a proxy dialer from golang.org/x/net/proxy and passing it to the mail client's options. ```go package main import ( "context" "log" "net" "github.com/wneessen/go-mail" "golang.org/x/net/proxy" ) func main() { message := mail.NewMsg() if err := message.From("toni.sender@example.com"); err != nil { log.Fatalf("failed to set From address: %s", err) } if err := message.To("tina.recipient@example.com"); err != nil { log.Fatalf("failed to set To address: %s", err) } message.Subject("This is my first mail with go-mail!") message.SetBodyString(mail.TypeTextPlain, "Do you like this mail? I certainly do!") dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:1080", nil, proxy.Direct) if err != nil { log.Fatalf("failed to create SOCKS5 proxy: %s", err) } client, err := mail.NewClient("smtp.example.com", mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithUsername("my_username"), mail.WithPassword("extremely_secret_pass"), mail.WithDialContextFunc(func(_ context.Context, network, addr string) (net.Conn, error) { return dialer.Dial(network, addr) }), ) if err != nil { log.Fatalf("failed to create mail client: %s", err) } if err := client.DialAndSend(message); err != nil { log.Fatalf("failed to send mail: %s", err) } } ``` -------------------------------- ### QQMailQuitErrorHandler for Tencent SMTP Source: https://github.com/wneessen/go-mail/wiki/Error-Registry Handles the specific error where smtp.qq.com returns arbitrary binary data after the QUIT command. This handler consumes the unexpected bytes before the standard '221 Bye' response is processed. ```go // QQMailQuitErrorHandler handles the common error for smtp.qq.com that returns arbitrary binary data after // the QUIT command, before returning the expected "221 Bye" response type QQMailQuitErrorHandler struct{} func (q *QQMailQuitErrorHandler) HandleError(_, _ string, conn *textproto.Conn, err error) error { var tpErr textproto.ProtocolError if errors.As(err, &tpErr) { if len(tpErr.Error()) < 16 { return err } if !bytes.Equal([]byte(tpErr.Error()[16:]), []byte("\x00\x00\x00\x1a\x00\x00\x00")) { return err } _, _ = io.ReadFull(conn.R, make([]byte, 8)) return nil } return err } ``` -------------------------------- ### GPG Public Key for Security Reports Source: https://github.com/wneessen/go-mail/wiki/Security This is the OpenPGP/GPG public key for sending encrypted security reports to security@go-mail.dev. Ensure your communication is encrypted using this key. ```text -----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY8RwPBYJKwYBBAHaRw8BAQdAiLsW7pv+CCMq5Ol0hbIB1HnJI97u3zJw Wslr7GJzgOzNK3NlY3VyaXR5QGdvLW1haWwuZGV2IDxzZWN1cml0eUBnby1t YWlsLmRldj7CjAQQFgoAPgUCY8RwPAQLCQcICRCgTBOxf8keAAMVCAoEFgAC AQIZAQIbAwIeARYhBAoWEB7Y0bE7zcIOuaBME7F/yR4AAAByugD9HabWXsyD aPIDrIS97OBA1OLltB4NPT5ba9whKRxTEmMBALBiB2ML4ZTrjLqI6UbGkhJq mWeMtvmU0chZT7WNBO0PzjgEY8RwPBIKKwYBBAGXVQEFAQEHQGDEccz6gvl5 t8cMMb/Dy2l0elRZL+Nd0gOhnbWMWlArAwEIB8J4BBgWCAAqBQJjxHA8CRCg TBOxf8keAAIbDBYhBAoWEB7Y0bE7zcIOuaBME7F/yR4AAADaMwD9EvEA3NSN NtdSaeL/euh6oRRiCjKzh5bIqZiQXqMlIOoBAJvPE2facs8MISwTtDoHW0sD WdOs3yBpGlGCs5WEqvQH =zn96 -----END PGP PUBLIC KEY BLOCK----- ``` -------------------------------- ### OpenPGP/GPG Public Key Source: https://github.com/wneessen/go-mail/blob/main/SECURITY.md This is the public key for sending encrypted emails to the security@go-mail.dev address. Ensure your email client is configured to use PGP/GPG for encryption. ```text -----BEGIN PGP PUBLIC KEY BLOCK----- ... -----END PGP PUBLIC KEY BLOCK----- ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.