Debian Codegraph @

pkg/services/email/smtp/doc.go

raw
1 // Package smtp provides a service for sending email notifications via the Simple Mail Transfer Protocol (SMTP).
2 // It is part of the shoutrrr notification framework and supports sending notifications to email recipients with configurable
3 // authentication, encryption, and message formatting options.
4 //
5 // The package supports the following features:
6 // - Authentication methods: None, Plain, Login, CRAM-MD5, and OAuth2.
7 // - Encryption methods: None, ExplicitTLS (using STARTTLS), ImplicitTLS (TLS for the entire session), and Auto (port-based selection).
8 // - Message formats: Plain text or HTML with multipart/alternative support.
9 // - Configuration via a URL scheme (e.g., `smtp://user:password@host:port/[email protected]&[email protected]`).
10 // - Integration with the shoutrrr framework for extensible notification delivery.
11 //
12 // # Usage
13 //
14 // To use the SMTP service, you must initialize a [Service] instance with a valid configuration URL and a logger.
15 // The configuration URL specifies the SMTP server details, authentication credentials, and email parameters.
16 // Below is an example of how to initialize and send an email notification:
17 //
18 // package main
19 //
20 // import (
21 // "log"
22 // "net/url"
23 // "github.com/nicholas-fedor/shoutrrr/pkg/services/email/smtp"
24 // "github.com/nicholas-fedor/shoutrrr/pkg/types"
25 // )
26 //
27 // func main() {
28 // logger := log.New(log.Writer(), "smtp: ", log.LstdFlags)
29 // service := &smtp.Service{}
30 //
31 // serviceURL, err := url.Parse("smtp://user:[email protected]:587/[email protected]&[email protected]&subject=Test%20Notification&useStartTLS=yes&useHTML=no")
32 // if err != nil {
33 // log.Fatalf("Failed to parse URL: %v", err)
34 // }
35 //
36 // err = service.Initialize(serviceURL, logger)
37 // if err != nil {
38 // log.Fatalf("Failed to initialize service: %v", err)
39 // }
40 //
41 // err = service.Send("This is a test notification.", nil)
42 // if err != nil {
43 // log.Fatalf("Failed to send notification: %v", err)
44 // }
45 // log.Println("Notification sent successfully!")
46 // }
47 //
48 // # Configuration
49 //
50 // The [Config] struct defines the parameters for the SMTP service, which can be set via a URL or programmatically.
51 // Key configuration fields include:
52 // - Host: The SMTP server hostname or IP address.
53 // - Port: The SMTP server port (e.g., 25, 465, 587, or 2525).
54 // - Username and Password: Credentials for authentication (if required).
55 // - FromAddress and FromName: The sender's email address and display name.
56 // - ToAddresses: A list of recipient email addresses.
57 // - Subject: The email subject (empty when omitted).
58 // - Auth: The authentication method (None, Plain, Login, CRAMMD5, OAuth2, or Unknown).
59 // - Encryption: The encryption method (None, ExplicitTLS, ImplicitTLS, or Auto).
60 // - UseStartTLS: Whether to use STARTTLS for encryption (default: true).
61 // - UseHTML: Whether to send the message as HTML (default: false).
62 // - ClientHost: The client hostname used in the SMTP handshake (default: "localhost").
63 // - RequireStartTLS: Whether to fail if StartTLS is enabled but unsupported (default: false).
64 // - SkipTLSVerify: Whether to skip TLS certificate verification (default: false).
65 // - Timeout: Duration for SMTP operations timeout (default: 10 seconds).
66 //
67 // The configuration URL follows the format:
68 //
69 // `smtp://<username>:<password>@<host>:<port>/?fromAddress=<email>&toAddresses=<email1>,<email2>&subject=<subject>&auth=<auth>&encryption=<encryption>&useStartTLS=<yes/no>&useHTML=<yes/no>&clientHost=<hostname>&requirestarttls=<yes/no>&skiptlsverify=<yes/no>&timeout=<duration>`
70 //
71 // Example URL:
72 //
73 // `smtp://user:[email protected]:587/[email protected]&[email protected],[email protected]&subject=Alert&auth=Plain&encryption=Auto&useStartTLS=yes&useHTML=yes&clientHost=localhost&requirestarttls=yes&skiptlsverify=no&timeout=10s`
74 //
75 // # Error Handling
76 //
77 // The package defines a set of failure identifiers in `smtp_failures.go` (e.g., [FailGetSMTPClient], [FailAuthenticating], [FailSendRecipient])
78 // to categorize errors that may occur during SMTP operations. These are wrapped using the [failures.Failure] interface
79 // from the Shoutrrr framework, providing detailed error messages and IDs for debugging.
80 //
81 // # Authentication
82 //
83 // The package supports multiple authentication methods, defined in [authType] and [AuthTypes]:
84 // - None: No authentication.
85 // - Plain: Username and password-based authentication.
86 // - Login: Username and password-based authentication via [newLoginAuth]. Useful if mail servers don't support AUTH PLAIN.
87 // - CRAMMD5: Challenge-response authentication using CRAM-MD5.
88 // - OAuth2: Token-based authentication for services like Gmail (see [newOAuth2Auth]).
89 // Note that OAuth2 support is limited to static access tokens and does not
90 // handle token refresh. A 334 challenge is answered with an empty continuation.
91 // - Unknown: Fallback when the authentication method is not specified or invalid.
92 //
93 // # Encryption
94 //
95 // Encryption is configured via the [encMethod] type and [EncMethods] helper, supporting:
96 // - None: No encryption.
97 // - ExplicitTLS: Uses STARTTLS to initiate a secure connection.
98 // - ImplicitTLS: Uses TLS for the entire session (typically on port 465).
99 // - Auto: Automatically selects ImplicitTLS for port [ImplicitTLSPort], otherwise attempts ExplicitTLS if supported.
100 //
101 // The [useImplicitTLS] function determines whether ImplicitTLS should be used based on the encryption method and port.
102 //
103 // # Testing
104 //
105 // The `smtp_test.go` file includes unit and integration tests using the Ginkgo and Gomega frameworks.
106 // Tests cover configuration parsing, email sending, error handling, and integration scenarios with mocked SMTP server responses.
107 // The [testIntegration] and [testSendRecipient] functions simulate SMTP server interactions for testing purposes.
108 //
109 // # Notes
110 //
111 // - The package uses [smtp.Client] from net/smtp for SMTP operations.
112 // - It supports multipart email messages (plain text and HTML) using a randomly generated boundary.
113 // - The [Service] struct implements the shoutrrr [standard.Standard] and [standard.Templater] interfaces for logging and message templating.
114 // - The package handles plus signs (`+`) in email addresses correctly, replacing spaces with plus signs as needed (see [Config.restorePlusAddresses]).
115 // - For OAuth2 authentication, [newOAuth2Auth] implements the SASL XOAUTH2 protocol, suitable for services like Gmail.
116 package smtp