### Complete Email Setup with Discovery Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Guides through discovering email settings, extracting server information, creating a `MailAccount`, and connecting to the mail server. ```dart import 'package:enough_mail/enough_mail.dart'; Future setupEmail(String email, String password) async { // 1. Discover settings final config = await Discover.discover(email); if (config == null) { print('Unable to auto-discover settings for $email'); return; } // 2. Extract information print('Provider: ${config.displayName}'); final incomingServer = config.preferredIncomingServer!; final outgoingServer = config.preferredOutgoingServer!; // 3. Create account final account = MailAccount.fromManualSettingsWithAuth( name: 'My Email', email: email, incomingHost: incomingServer.hostname, incomingPort: incomingServer.port, incomingSocketType: incomingServer.socketType == SocketType.ssl ? SocketType.ssl : SocketType.startTls, incomingType: incomingServer.type == ServerType.pop ? ServerType.pop : ServerType.imap, outgoingHost: outgoingServer.hostname, outgoingPort: outgoingServer.port, outgoingSocketType: outgoingServer.socketType, auth: PlainAuthentication(email, password), ); // 4. Connect and use final client = MailClient(account); try { await client.connect(); final mailboxes = await client.listMailboxes(); print('Connected! Found ${mailboxes.length} mailboxes'); } catch (e) { print('Connection failed: $e'); } } ``` -------------------------------- ### Import enough_mail Library Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Import the necessary library to start using enough_mail. ```dart import 'package:enough_mail/enough_mail.dart'; ``` -------------------------------- ### Example MailClient Configuration Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/configuration.md Demonstrates how to instantiate and connect a MailClient with custom settings. Ensure MailAccount is configured before creating the client. ```dart final account = MailAccount.fromManualSettings( name: 'My Email', email: 'user@example.com', incomingHost: 'imap.example.com', outgoingHost: 'smtp.example.com', password: 'password', ); final client = MailClient( account, isLogEnabled: true, downloadSizeLimit: 10 * 1024 * 1024, // 10 MB logName: 'WorkEmail', defaultWriteTimeout: Duration(seconds: 5), defaultResponseTimeout: Duration(seconds: 10), ); await client.connect(); ``` -------------------------------- ### Migrated IMAP Client Code Example Source: https://github.com/enough-software/enough_mail/blob/main/migration.md This is the migrated code example for interacting with an IMAP server, demonstrating the simplified approach with exception handling. ```dart final client = ImapClient(isLogEnabled: false); try { await client.connectToServer(imapServerHost, imapServerPort, isSecure: isImapServerSecure); await client.login(userName, password); final mailboxes = await client.listMailboxes(); print('mailboxes: ${mailboxes}'); await client.selectInbox(); // fetch 10 most recent messages: final fetchResult = await client.fetchRecentMessages( messageCount: 10, criteria: 'BODY.PEEK[]'); for (var message in fetchResult.messages) { printMessage(message); } await client.logout(); } on ImapException catch (e) { print('imap failed with $e'); } ``` -------------------------------- ### Server Type Name Example Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Shows how to access the human-readable server type name, such as IMAP, SMTP, or POP3. ```dart print(serverConfig.typeName); // "IMAP", "SMTP", "POP3" ``` -------------------------------- ### Example: Sending a Test Email Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Demonstrates how to construct a multipart alternative message with plain text and HTML content, set headers, and send it using the mail client. ```dart final builder = MessageBuilder.prepareMultipartAlternativeMessage( plainText: 'Hello!', htmlText: '

Hello!

', ) ..from = [MailAddress('Me', 'sender@example.com')] ..to = [MailAddress('You', 'recipient@example.com')] ..subject = 'Test'; final message = builder.buildMimeMessage(); await client.sendMessage(message); ``` -------------------------------- ### High-Level Mail API Usage Example Source: https://github.com/enough-software/enough_mail/blob/main/README.md Demonstrates connecting to an email account using auto-discovered settings, fetching messages, and sending a newly built message. It also shows how to listen for new incoming messages. ```dart import 'dart:io'; import 'package:enough_mail/enough_mail.dart'; String userName = 'user.name'; String password = 'password'; void main() async { await mailExample(); } /// Builds a simple example message MimeMessage buildMessage() { final builder = MessageBuilder.prepareMultipartAlternativeMessage( plainText: 'Hello world!', htmlText: '

Hello world!

', ) ..from = [MailAddress('Personal Name', 'sender@domain.com')] ..to = [ MailAddress('Recipient Personal Name', 'recipient@domain.com'), MailAddress('Other Recipient', 'other@domain.com') ]; return builder.buildMimeMessage(); } /// Builds an example message with attachment Future buildMessageWithAttachment() async { final builder = MessageBuilder() ..from = [MailAddress('Personal Name', 'sender@domain.com')] ..to = [ MailAddress('Recipient Personal Name', 'recipient@domain.com'), MailAddress('Other Recipient', 'other@domain.com') ] ..addMultipartAlternative( plainText: 'Hello world!', htmlText: '

Hello world!

', ); final file = File.fromUri(Uri.parse('file://./document.pdf')); await builder.addFile(file, MediaSubtype.applicationPdf.mediaType); return builder.buildMimeMessage(); } /// High level mail API example Future mailExample() async { final email = '$userName@$domain'; print('discovering settings for $email...'); final config = await Discover.discover(email); if (config == null) { // note that you can also directly create an account when // you cannot auto-discover the settings: // Compare the [MailAccount.fromManualSettings] // and [MailAccount.fromManualSettingsWithAuth] // methods for details. print('Unable to auto-discover settings for $email'); return; } print('connecting to ${config.displayName}.'); final account = MailAccount.fromDiscoveredSettings('my account', email, password, config); final mailClient = MailClient(account, isLogEnabled: true); try { await mailClient.connect(); print('connected'); final mailboxes = await mailClient.listMailboxesAsTree(createIntermediate: false); print(mailboxes); await mailClient.selectInbox(); final messages = await mailClient.fetchMessages(count: 20); messages.forEach(printMessage); mailClient.eventBus.on().listen((event) { print('New message at ${DateTime.now()}:'); printMessage(event.message); }); await mailClient.startPolling(); // generate and send email: final mimeMessage = buildMessage(); await mailClient.sendMessage(mimeMessage); } on MailException catch (e) { print('High level API failed with $e'); } } ``` -------------------------------- ### startPolling Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Starts listening for new incoming messages. Fires MailLoadEvent on new messages. The polling interval can be customized. ```APIDOC ## startPolling() ### Description Starts listening for new incoming messages. Fires `MailLoadEvent` on new messages. ### Method `Future` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### duration - **duration** (Duration) - Optional - Polling interval. Defaults to 2 minutes. ### Example ```dart client.eventStream.listen((event) { if (event is MailLoadEvent) { print('New message: ${event.message.decodeSubject()}'); } }); await client.startPolling(Duration(minutes: 5)); ``` ``` -------------------------------- ### Old IMAP Client Code Example Source: https://github.com/enough-software/enough_mail/blob/main/migration.md This is the old code example for interacting with an IMAP server, which involves checking response statuses at each step. ```dart final client = ImapClient(isLogEnabled: false); await client.connectToServer(imapServerHost, imapServerPort, isSecure: isImapServerSecure); final loginResponse = await client.login(userName, password); if (loginResponse.isOkStatus) { final listResponse = await client.listMailboxes(); if (listResponse.isOkStatus) { print('mailboxes: ${listResponse.result}'); final inboxResponse = await client.selectInbox(); if (inboxResponse.isOkStatus) { // fetch 10 most recent messages: final fetchResponse = await client.fetchRecentMessages( messageCount: 10, criteria: 'BODY.PEEK[]'); if (fetchResponse.isOkStatus) { final messages = fetchResponse.result.messages; for (var message in messages) { printMessage(message); } } } } await client.logout(); } ``` -------------------------------- ### MailAddress Class Definition and Example Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/types.md Defines an email address with an optional personal name and provides an example of its creation and usage. ```dart class MailAddress { /// Personal name (e.g., "John Doe") final String? personalName; /// Email address (e.g., "john@example.com") final String email; /// Creates a new mail address MailAddress(this.personalName, this.email); } final addr = MailAddress('John Doe', 'john@example.com'); print('${addr.personalName} <${addr.email}>'); // John Doe ``` -------------------------------- ### getUserName Method Example Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Demonstrates how to derive a login username from an email address based on the configured username type. ```dart String? getUserName(String email) ``` ```dart final username = serverConfig.getUserName('john@example.com'); // If usernameType == emailAddress: 'john@example.com' // If usernameType == domain: 'example.com' // If usernameType == username: 'john' ``` -------------------------------- ### Example: Printing Mailbox Tree Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/types.md Demonstrates how to traverse and print a mailbox hierarchy represented by the Tree structure. Requires the Tree and TreeElement classes to be defined. ```dart final tree = await client.listMailboxesAsTree(); void printTree(TreeElement elem, int indent) { if (elem.value != null) { print('${' ' * indent}${elem.value!.name}'); } for (final child in elem.children ?? []) { printTree(child, indent + 1); } } printTree(tree.root, 0); ``` -------------------------------- ### Install Enough Mail Package Source: https://github.com/enough-software/enough_mail/blob/main/README.md Add the enough_mail package to your pubspec.yaml file to include it in your project dependencies. ```yaml dependencies: enough_mail: ^2.2.0 ``` -------------------------------- ### Initialize MessageBuilder with Sender, Recipients, and Subject Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/messagebuilder.md Demonstrates initializing a MessageBuilder with sender, recipient, and subject details. This is a common starting point for constructing an email. ```dart final builder = MessageBuilder() ..from = [MailAddress('John Doe', 'john@example.com')] ..to = [MailAddress('Jane Doe', 'jane@example.com')] ..subject = 'Hello'; ``` -------------------------------- ### Low-Level POP3 Client Usage Source: https://github.com/enough-software/enough_mail/blob/main/README.md Connect to a POP3 server, log in, retrieve server status, list messages, and fetch a specific message. Includes an example of attempting to retrieve a non-existent message. ```dart /// Low level POP3 API example Future popExample() async { final client = PopClient(isLogEnabled: false); try { await client.connectToServer(popServerHost, popServerPort, isSecure: isPopServerSecure); await client.login(userName, password); // alternative login: // await client.loginWithApop(userName, password); // optional different login mechanism final status = await client.status(); print( 'status: messages count=${status.numberOfMessages}, messages size=${status.totalSizeInBytes}'); final messageList = await client.list(status.numberOfMessages); print( 'last message: id=${messageList?.first?.id} size=${messageList?.first?.sizeInBytes}'); var message = await client.retrieve(status.numberOfMessages); printMessage(message); message = await client.retrieve(status.numberOfMessages + 1); print('trying to retrieve newer message succeeded'); await client.quit(); } on PopException catch (e) { print('POP failed with $e'); } } ``` -------------------------------- ### MailAccount.fromDiscoveredSettings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md Creates an account from auto-discovered settings using plain authentication, simplifying setup when server details are not known beforehand. ```APIDOC ## MailAccount.fromDiscoveredSettings Factory Constructor ### Description Creates an account from auto-discovered settings with plain authentication. ### Method Signature ```dart factory MailAccount.fromDiscoveredSettings({ required String name, required String email, required String password, required ClientConfig config, required String userName, String outgoingClientDomain = 'enough.de', String? loginName, bool supportsPlusAliases = false, List aliases = const [], }) ``` ### Parameters Details - **name** (String) - Required - Account display name - **email** (String) - Required - User's email address - **password** (String) - Required - Login password (auto-encrypted if using TLS) - **config** (ClientConfig) - Required - Discovery configuration from Discover.discover() - **userName** (String) - Required - Display name - **outgoingClientDomain** (String) - Optional - SMTP client domain - **loginName** (String?) - Optional - Custom login name (defaults to extracted from email or config) - **supportsPlusAliases** (bool) - Optional - Plus alias support - **aliases** (List) - Optional - Alternative addresses ### Request Example ```dart final config = await Discover.discover('user@example.com'); final account = MailAccount.fromDiscoveredSettings( name: 'Work Email', email: 'user@example.com', password: 'mypassword', config: config, userName: 'John Doe', ); ``` ``` -------------------------------- ### fromManualSettings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md Creates a MailAccount instance from manual server configuration with plain authentication. This factory constructor allows for detailed setup of both incoming and outgoing mail server parameters. ```APIDOC ## fromManualSettings() ### Description Creates an account from manual server configuration with plain authentication. ### Method Signature ```dart factory MailAccount.fromManualSettings({ required String name, required String email, required String incomingHost, required String outgoingHost, required String password, String userName = '', ServerType incomingType = ServerType.imap, ServerType outgoingType = ServerType.smtp, String? loginName, String outgoingClientDomain = 'enough.de', int incomingPort = 993, int outgoingPort = 465, SocketType incomingSocketType = SocketType.ssl, SocketType outgoingSocketType = SocketType.ssl, bool supportsPlusAliases = false, List aliases = const [], }) ``` ### Parameters - **name** (String) - Required - The display name for the account. - **email** (String) - Required - The email address for this account. - **incomingHost** (String) - Required - IMAP/POP3 server hostname. - **outgoingHost** (String) - Required - SMTP server hostname. - **password** (String) - Required - Login password. - **userName** (String) - Optional - User's display name (e.g., "John Doe"). Defaults to an empty string. - **incomingType** (ServerType) - Optional - IMAP or POP3. Defaults to `ServerType.imap`. - **outgoingType** (ServerType) - Optional - Outgoing server type. Defaults to `ServerType.smtp`. - **loginName** (String?) - Optional - Custom login name. Defaults to null. - **outgoingClientDomain** (String) - Optional - Domain reported to SMTP server. Defaults to 'enough.de'. - **incomingPort** (int) - Optional - IMAP/POP3 port. Defaults to 993. - **outgoingPort** (int) - Optional - SMTP port. Defaults to 465. - **incomingSocketType** (SocketType) - Optional - TLS/SSL for incoming connections. Defaults to `SocketType.ssl`. - **outgoingSocketType** (SocketType) - Optional - TLS/SSL for outgoing connections. Defaults to `SocketType.ssl`. - **supportsPlusAliases** (bool) - Optional - Indicates if the mail service supports plus-based aliases. Defaults to false. - **aliases** (List) - Optional - List of alternative email addresses for this account. Defaults to an empty list. ### Example ```dart final account = MailAccount.fromManualSettings( name: 'Gmail', email: 'user@gmail.com', incomingHost: 'imap.gmail.com', outgoingHost: 'smtp.gmail.com', password: 'app-password', userName: 'John Doe', ); ``` ``` -------------------------------- ### SearchCriteriaBuilder Example Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/types.md Illustrates the usage of the fluent SearchCriteriaBuilder to construct complex IMAP search queries. This builder allows chaining methods to specify various search parameters. ```dart final criteria = SearchCriteriaBuilder() .text('example') .flagged() .seenInLast(Duration(days: 7)) .get(); ``` -------------------------------- ### Get Login Name Utility Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md A static utility function to determine the correct login name based on email and server configuration rules. ```dart static String getLoginName(String email, ServerConfig serverConfig) ``` -------------------------------- ### Auto-Discover Email Provider Settings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Automatically discover the mail server configuration for a given email address. This simplifies setup by eliminating the need for manual server configuration. ```dart final config = await Discover.discover('user@example.com'); final provider = config?.displayName; // e.g., "Gmail" ``` -------------------------------- ### Create an Empty MessageBuilder Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/messagebuilder.md Use the default constructor to create an empty message builder. This is useful for starting a new message from scratch and setting its properties sequentially. ```dart MessageBuilder() ``` -------------------------------- ### Build a Message with File Attachment Source: https://github.com/enough-software/enough_mail/blob/main/README.md Creates a MIME message that includes a file attachment. This example demonstrates how to add a PDF file to the message using the MessageBuilder. ```dart /// Builds an example message with attachment Future buildMessageWithAttachment() async { final builder = MessageBuilder() ..from = [MailAddress('Personal Name', 'sender@domain.com')] ..to = [ MailAddress('Recipient Personal Name', 'recipient@domain.com'), MailAddress('Other Recipient', 'other@domain.com') ] ..addMultipartAlternative( plainText: 'Hello world!', htmlText: '

Hello world!

', ); final file = File.fromUri(Uri.parse('file://./document.pdf')); await builder.addFile(file, MediaSubtype.applicationPdf.mediaType); return builder.buildMimeMessage(); } ``` -------------------------------- ### Watch for New Email Messages and Events Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Sets up a listener for the client's event stream to react to new messages or connection events. It then starts polling the server for new messages at a specified interval. ```dart client.eventStream.listen((event) { if (event is MailLoadEvent) { print('New: ${event.message.decodeSubject()}'); } else if (event is MailConnectionLostEvent) { print('Connection lost, reconnecting...'); } }); await client.startPolling(Duration(minutes: 2)); ``` -------------------------------- ### Connect and Send with SmtpClient Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Demonstrates how to establish an SMTP connection, authenticate, and send a message using the SmtpClient. ```dart final client = SmtpClient('example.com'); await client.connectToServer('smtp.gmail.com', 465, isSecure: true); await client.ehlo(); await client.authenticate('user', 'password', AuthMechanism.plain); await client.sendMessage(message); ``` -------------------------------- ### Start Polling for New Messages Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Starts listening for new incoming messages and fires MailLoadEvent on new messages. Configure the polling interval using the duration parameter. ```dart client.eventStream.listen((event) { if (event is MailLoadEvent) { print('New message: ${event.message.decodeSubject()}'); } }); await client.startPolling(Duration(minutes: 5)); ``` -------------------------------- ### Get MailAddress from MailAccount Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md The `fromAddress` property provides a convenient way to get a MailAddress object composed of the account's userName and email. This is useful for setting the 'From' field in outgoing emails. ```dart final fromAddr = account.fromAddress; // MailAddress('John Doe', 'user@example.com') ``` -------------------------------- ### Fallback to Manual Configuration Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Illustrates how to attempt discovery and fall back to manual email account settings if auto-discovery fails. ```dart Future setupEmailManual() async { try { final config = await Discover.discover('user@example.com'); if (config != null) { // Use discovered settings // ... } else { // Fallback to manual entry final account = MailAccount.fromManualSettings( name: 'Custom Email', email: 'user@example.com', incomingHost: 'mail.example.com', outgoingHost: 'mail.example.com', password: 'password', incomingPort: 993, outgoingPort: 587, incomingSocketType: SocketType.ssl, outgoingSocketType: SocketType.startTls, ); } } catch (e) { print('Discovery error: $e'); // Show manual entry form to user } } ``` -------------------------------- ### Connect and Retrieve with PopClient Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Shows how to connect to a POP3 server, log in, and retrieve email status and messages using PopClient. ```dart final client = PopClient(); await client.connectToServer('pop.gmail.com', 995); await client.login('user', 'password'); final status = await client.status(); final message = await client.retrieve(1); ``` -------------------------------- ### Enable IMAP IDLE for Real-time Push Notifications Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/configuration.md Connect to the mail server and start polling for new messages. The client can utilize the IDLE extension for real-time push notifications if supported by the server, triggering event listeners for new mail. ```dart final client = MailClient(account); await client.connect(); await client.startPolling(); // Or use IDLE if supported client.eventStream.listen((event) { if (event is MailLoadEvent) { print('New message: ${event.message.subject}'); } }); ``` -------------------------------- ### Get Cached Mailboxes Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Retrieves a list of mailboxes that were previously cached during the last call to listMailboxes(). ```dart List? get mailboxes => _mailboxes; ``` -------------------------------- ### Connect to Mail Server Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Initialize and connect a MailClient to the email server using the configured MailAccount. ```dart final client = MailClient(account); await client.connect(); ``` -------------------------------- ### MessageBuilder() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/messagebuilder.md Creates an empty message builder instance. This is the starting point for constructing a new email message. ```APIDOC ## MessageBuilder() ### Description Creates an empty message builder. ### Method Constructor ### Parameters None ### Request Example ```dart final builder = MessageBuilder() ..from = [MailAddress('John Doe', 'john@example.com')] ..to = [MailAddress('Jane Doe', 'jane@example.com')] ..subject = 'Hello'; ``` ``` -------------------------------- ### Get Selected Mailbox Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Retrieves the currently selected mailbox. Returns null if no mailbox is currently selected. ```dart Mailbox? get selectedMailbox => _selectedMailbox; ``` -------------------------------- ### PopClient.connectToServer Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Establishes a connection to the POP3 server. ```APIDOC ## connectToServer() PopClient ### Description Connects to the POP3 server using the provided host and port. Supports secure connections. ### Method `connectToServer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **host** (String) - Required - The hostname or IP address of the POP3 server. * **port** (int) - Required - The port number for the POP3 server. * **isSecure** (bool) - Optional - Defaults to `true`. If true, uses a secure connection (e.g., POP3S/SSL/TLS). ``` -------------------------------- ### Get Message In-Reply-To ID Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md The `inReplyToMessageId` property returns the Message-ID of the email this message is a reply to. It is nullable. ```dart if (message.inReplyToMessageId != null) { print('In reply to: ${message.inReplyToMessageId}'); } ``` -------------------------------- ### connect() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Connects and authenticates with the incoming mail server. Handles OAuth token refresh if configured. Throws MailException on connection or authentication failure. ```APIDOC ## connect() ### Description Connects and authenticates with the incoming mail server. Handles OAuth token refresh if configured. ### Method `Future connect({Duration timeout = const Duration(seconds: 20)})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Details - **timeout** (Duration) - Optional - Connection timeout (default: 20 seconds) ### Throws - `MailException` on connection or authentication failure. ### Example ```dart final client = MailClient(account); try { await client.connect(); print('Connected'); } on MailException catch (e) { print('Connection failed: $e'); } ``` ``` -------------------------------- ### startTls() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Upgrades an existing plain text SMTP connection to a secure TLS connection. Typically used for port 587. ```APIDOC ## startTls() ### Description Upgrades to TLS (for port 587). ### Method `Future startTls()` ``` -------------------------------- ### idleStart() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Initiates IMAP IDLE mode, enabling real-time notifications for server events. Events are streamed via an event bus. ```APIDOC ## idleStart() ### Description Starts IMAP IDLE mode for real-time notifications. Stream events via eventBus. ### Method `Future idleStart()` ``` -------------------------------- ### Configure Custom On-Premises Server Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/configuration.md Configure an on-premises email server using manual settings. Adjust login name for Windows authentication if necessary. ```dart final account = MailAccount.fromManualSettings( name: 'Company Email', email: 'user@company.com', incomingHost: 'mail.company.com', outgoingHost: 'mail.company.com', password: 'password', incomingPort: 993, outgoingPort: 587, incomingSocketType: SocketType.ssl, outgoingSocketType: SocketType.startTls, userName: 'John Doe', loginName: 'user', // Or 'DOMAIN\user' for Windows auth ); ``` -------------------------------- ### Get All Attachments Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md The `getAttachments` method returns a list of `MimePart` objects representing all non-inline, non-text attachments in the message. ```dart for (final attachment in message.getAttachments()) { final fileName = attachment.decodeFileName(); print('Attachment: $fileName'); } ``` -------------------------------- ### ImapClient.startTls Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Upgrades the current connection to use TLS encryption. This should be called before login if the initial connection was not secure. ```APIDOC ## ImapClient.startTls ### Description Upgrades connection to TLS (STARTTLS). Call before login for non-SSL connections. ### Method Future ### Endpoint startTls() ### Parameters None ### Request Example ```dart await client.startTls(); ``` ``` -------------------------------- ### Retrieve Thread References Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Access the `references` property to get a list of Message-IDs for all messages in the thread. This property is nullable. ```dart print('Thread references: ${message.references?.join(', ')}'); ``` -------------------------------- ### Mailbox hasFlag Method Example Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/types.md Checks if a mailbox possesses a specific IMAP flag. This is useful for determining mailbox characteristics. ```dart if (mailbox.hasFlag(MailboxFlag.inbox)) { print('This is the inbox'); } ``` -------------------------------- ### Add and Commit Changes Source: https://github.com/enough-software/enough_mail/blob/main/README.md Stage all changes and commit them to your local repository before pushing. Use `git add -A` to stage all modified files. ```bash git add -A git commit ``` -------------------------------- ### Get POP3 Mailbox Status Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Retrieves the status of the POP3 mailbox, including the total number of messages and their combined size. ```dart Future status() ``` ```dart final status = await client.status(); print('Messages: ${status.numberOfMessages}'); print('Total size: ${status.totalSizeInBytes} bytes'); ``` -------------------------------- ### Discover Mail Server Configuration Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Use the static discover method to automatically find mail server settings for a given email address. Enable isLogEnabled for detailed debug logs during the process. ```dart static Future discover( String email, { bool isLogEnabled = false, }) ``` ```dart final config = await Discover.discover('user@gmail.com'); if (config != null) { print('Email provider: ${config.displayName}'); for (final provider in config.emailProviders) { print('- Incoming: ${provider.preferredIncomingServer}'); print('- Outgoing: ${provider.preferredOutgoingServer}'); } } ``` -------------------------------- ### Header Operations Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Provides methods for getting, setting, adding, and removing email headers, as well as decoding header values. ```APIDOC ## Header Operations ### getHeaderValue(String name): String? Gets raw value of a header (may be RFC 2047 encoded). ### decodeHeaderValue(String name): String? Gets decoded header value (automatic RFC 2047 decoding). ### decodeHeaderMailAddressValue(String name): List? Decodes an email address header. ### decodeHeaderDateValue(String name): DateTime? Decodes a date header to DateTime. ### getHeader(String name): Iterable
? Gets all headers with given name (allows duplicates). ### hasHeader(String name): bool Checks if a header exists. ### addHeader(String name, String? value, [HeaderEncoding encoding]) Adds a header to the message. ### setHeader(String name, String? value, [HeaderEncoding encoding]) Sets a header, replacing existing header with same name. ### removeHeader(String name) Removes all headers with given name. ``` -------------------------------- ### Clone Enough Mail Repository Source: https://github.com/enough-software/enough_mail/blob/main/README.md Clone the Enough Mail project to your local machine to begin development. Ensure you replace `$your_username` with your actual GitHub username. ```bash git clone github.com/$your_username/enough_mail ``` -------------------------------- ### Get Content Information by Disposition Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Use `getContentInfo` with a `ContentDisposition` to fetch detailed information about parts of a specific type, such as attachments. ```dart final attachments = message.getContentInfo(ContentDisposition.attachment); for (final info in attachments) { print('${info.contentType?.mediaType.text}: ${info.fetchId}'); } ``` -------------------------------- ### Check Server Capabilities Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Connects to the mail server and prints its supported capabilities. This information is useful for understanding what features the server offers and how the client can interact with them. ```dart await client.connect(); print(client.lowLevelIncomingMailClient.serverInfo.capabilities); ``` -------------------------------- ### SocketType Enum Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Defines the connection types for email servers: plain (unencrypted), ssl (SSL/TLS from start), and startTls (upgrade to TLS). ```dart enum SocketType { plain, // Unencrypted (port 143, 25, 110) ssl, // SSL/TLS from start (port 993, 465, 995) startTls, // Upgrade to TLS (port 587, 143) } ``` -------------------------------- ### Create Mail Account from Discovered Settings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Create a MailAccount object using settings discovered automatically. Ensure the 'config' is not null. ```dart final account = MailAccount.fromDiscoveredSettings( name: 'My Email', email: 'user@example.com', password: 'mypassword', config: config!, userName: 'John Doe', ); ``` -------------------------------- ### Get All Content Parts Recursively Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md The `getAllContentParts` method retrieves all MIME parts within the message, including nested multipart structures. ```dart final allParts = message.getAllContentParts(); ``` -------------------------------- ### Get All Headers by Name Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Retrieve all headers matching a given name, including duplicates, using the `getHeader` method. It returns an `Iterable
`. ```dart final received = message.getHeader('received'); for (final header in received ?? []) { print(header.value); } ``` -------------------------------- ### MailClient Constructor Options Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/configuration.md Defines the available parameters for initializing the MailClient. Use these options to customize logging, timeouts, and callbacks. ```dart MailClient( MailAccount account, { bool isLogEnabled = false, int? downloadSizeLimit, String? logName, Duration defaultWriteTimeout = const Duration(seconds: 2), Duration defaultResponseTimeout = const Duration(seconds: 5), bool Function(X509Certificate)? onBadCertificate, Id? clientId, Future Function(MailClient client, OauthToken expiredToken)? refresh, Future Function(MailAccount account)? onConfigChanged, } ) ``` -------------------------------- ### Connect and Login with ImapClient Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Establish a direct connection to an IMAP server and log in using provided credentials. This low-level client is for advanced users who need direct protocol control. ```dart final client = ImapClient(); await client.connectToServer('imap.gmail.com', 993); await client.login('user', 'password'); final mailboxes = await client.listMailboxes(); ``` -------------------------------- ### Basic Message Inspection Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Fetches a list of messages and iterates through them to print sender, subject, and date. Requires client setup and message fetching. ```dart final messages = await client.fetchMessages(); for (final message in messages) { final from = message.from?.first?.email ?? 'unknown'; final subject = message.decodeSubject() ?? '(no subject)'; final date = message.decodeDate()?.toLocal() ?? 'unknown date'; print('From: $from'); print('Subject: $subject'); print('Date: $date'); print('---'); } ``` -------------------------------- ### Run All Tests Source: https://github.com/enough-software/enough_mail/blob/main/README.md Execute all test cases for the Enough Mail package to ensure code integrity. This command should be run after cloning the repository or making changes. ```bash dart run test ``` -------------------------------- ### Watch for New Messages with Polling Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Listen to the client's event stream for new mail events and start polling the server at a specified interval. ```dart client.eventStream.listen((event) { if (event is MailLoadEvent) { print('New: ${event.message.decodeSubject()}'); } }); await client.startPolling(Duration(minutes: 2)); ``` -------------------------------- ### Prepare and Send a Multipart Alternative Email Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Create a multipart email with both plain text and HTML versions. Set sender, recipient, and subject before building and sending. ```dart final message = MessageBuilder.prepareMultipartAlternativeMessage( plainText: 'Hello', htmlText: '

Hello

', ) ..from = [MailAddress('John', 'john@example.com')] ..to = [MailAddress('Jane', 'jane@example.com')] ..subject = 'Test'; await client.sendMessage(message.buildMimeMessage()); ``` -------------------------------- ### Get Mailbox by Flag Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailclient.md Retrieves a mailbox using its flag from a cached or provided list. Useful for accessing specific mailboxes like 'inbox' or 'sent'. ```dart Mailbox? getMailbox(MailboxFlag flag, [List? boxes]) ``` -------------------------------- ### Create MailAccount from Discovered Settings (Plain Auth) Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md Use this factory constructor to create a MailAccount when you have discovered server settings and are using plain password authentication. Ensure you have a ClientConfig obtained from Discover.discover(). ```dart factory MailAccount.fromDiscoveredSettings({ required String name, required String email, required String password, required ClientConfig config, required String userName, String outgoingClientDomain = 'enough.de', String? loginName, bool supportsPlusAliases = false, List aliases = const [], }) ``` ```dart final config = await Discover.discover('user@example.com'); final account = MailAccount.fromDiscoveredSettings( name: 'Work Email', email: 'user@example.com', password: 'mypassword', config: config, userName: 'John Doe', ); ``` -------------------------------- ### Connect to Gmail using Manual Settings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/README.md Configure and connect to Gmail using manual server settings. It's recommended to use an app-specific password for security. ```dart final account = MailAccount.fromManualSettings( name: 'Gmail', email: 'user@gmail.com', incomingHost: 'imap.gmail.com', outgoingHost: 'smtp.gmail.com', password: 'app-password', // Use app-specific password userName: 'John Doe', ); final client = MailClient(account); await client.connect(); ``` -------------------------------- ### Get Inline Attachments Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Retrieve a list of `MimePart` objects for inline attachments, typically used for embedding images in HTML emails, using `getInlineAttachments`. ```dart for (final inline in message.getInlineAttachments()) { final cid = inline.getHeaderValue('content-id'); print('Inline attachment with CID: $cid'); } ``` -------------------------------- ### Getting a Specific MIME Part Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Retrieves a specific MIME part using its fetch ID (e.g., '2') and decodes its text content if found. ```dart final part = message.getPart('2'); // Get part 2 if (part != null) { final text = part.decodeContentText(); } ``` -------------------------------- ### Inspecting All Available Servers Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Iterates through all discovered email providers and their incoming servers to print detailed connection information. ```dart final config = await Discover.discover('user@example.com'); for (final provider in config!.emailProviders) { for (final server in provider.incomingServers) { print('${server.typeName}: ${server.hostname}:${server.port}/${server.socketType.name}'); print(' Username: ${server.usernameType.name}'); print(' Auth: ${server.authentication.join(", ")}'); } } ``` -------------------------------- ### MailAccount Constructor Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md Creates a mail account with explicit server configurations for incoming and outgoing mail servers. ```APIDOC ## MailAccount Constructor ### Description Creates a mail account with explicit server configurations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```dart const MailAccount({ required String name, required String email, required MailServerConfig incoming, required MailServerConfig outgoing, String userName = '', String outgoingClientDomain = 'enough.de', bool supportsPlusAliases = false, List aliases = const [], Map attributes = const {}, }) ``` ### Parameters Details - **name** (String) - Required - Account display name (e.g., "Personal Email") - **email** (String) - Required - Email address of the account - **incoming** (MailServerConfig) - Required - IMAP or POP3 server configuration - **outgoing** (MailServerConfig) - Required - SMTP server configuration - **userName** (String) - Optional - User's display name (e.g., "John Doe") - **outgoingClientDomain** (String) - Optional - Domain reported to SMTP server - **supportsPlusAliases** (bool) - Optional - Whether service supports + based aliases (user+tag@domain) - **aliases** (List) - Optional - Alternative email addresses for this account - **attributes** (Map) - Optional - Custom attributes for application-specific data ``` -------------------------------- ### connectToServer() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Establishes a connection to the specified SMTP host and port. Supports secure (SSL/TLS) connections by default. ```APIDOC ## connectToServer() ### Description Connects to SMTP server. ### Method `Future connectToServer(String host, int port, {bool isSecure = true})` ### Parameters #### Path Parameters - **host** (String) - Required - Hostname - **port** (int) - Required - Port (465 for SSL, 25/587 for plain) - **isSecure** (bool) - Optional - Default: `true`. Use SSL/TLS. ``` -------------------------------- ### Get Raw Header Value Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mimemessage.md Use `getHeaderValue` to retrieve the raw string value of a specified email header. The value may be RFC 2047 encoded. ```dart final contentType = message.getHeaderValue('content-type'); ``` -------------------------------- ### Discover.discover() Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/discover.md Auto-discovers mail server configuration for a given email address. It attempts discovery through various methods including `.well-known/autoconfig.xml`, `autoconfig.domain` subdomain, Mozilla autoconfig service, and falls back to common provider configurations. Returns a `ClientConfig` object with server details or null if discovery fails. Can throw exceptions on network errors. ```APIDOC ## discover() ### Description Auto-discovers mail server configuration for an email address. ### Method `static Future discover(String email, {bool isLogEnabled = false})` ### Parameters #### Path Parameters None #### Query Parameters * **email** (String) - Required - Email address to discover settings for * **isLogEnabled** (bool) - Optional - Enable debug logging (default: false) ### Request Example ```dart final config = await Discover.discover('user@gmail.com'); if (config != null) { print('Email provider: ${config.displayName}'); for (final provider in config.emailProviders) { print('- Incoming: ${provider.preferredIncomingServer}'); print('- Outgoing: ${provider.preferredOutgoingServer}'); } } ``` ### Response #### Success Response * **ClientConfig?** - ClientConfig with server configurations, or null if discovery fails. #### Response Example ```json { "version": "1.1", "displayName": "Gmail", "domain": "gmail.com", "emailProviders": [ { "id": "gmail", "displayName": "Gmail", "domains": ["gmail.com", "googlemail.com"], "documentation": null, "documentationUrl": null, "incomingServers": [ { "type": "imap", "hostname": "imap.gmail.com", "port": 993, "socketType": "ssl", "usernameType": "emailAddress", "authentication": ["oauth2", "plain"] } ], "outcomingServers": [ { "type": "smtp", "hostname": "smtp.gmail.com", "port": 465, "socketType": "ssl", "usernameType": "emailAddress", "authentication": ["oauth2", "plain"] } ] } ] } ``` ### Throws Exception on network errors. ``` -------------------------------- ### ImapClient Constructor Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Initializes an ImapClient. Logging can be enabled, and timeouts can be configured. A callback for handling bad certificates is also available. ```dart ImapClient({ bool isLogEnabled = false, String? logName, Duration writeTimeout = const Duration(seconds: 2), Duration responseTimeout = const Duration(seconds: 5), bool Function(X509Certificate)? onBadCertificate, }) ``` -------------------------------- ### Create MailAccount from Manual Settings Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/mailaccount.md Use this factory constructor to create a MailAccount instance when you have all the incoming and outgoing server details. It supports plain authentication. ```dart factory MailAccount.fromManualSettings({ required String name, required String email, required String incomingHost, required String outgoingHost, required String password, String userName = '', ServerType incomingType = ServerType.imap, ServerType outgoingType = ServerType.smtp, String? loginName, String outgoingClientDomain = 'enough.de', int incomingPort = 993, int outgoingPort = 465, SocketType incomingSocketType = SocketType.ssl, SocketType outgoingSocketType = SocketType.ssl, bool supportsPlusAliases = false, List aliases = const [], }) ``` ```dart final account = MailAccount.fromManualSettings( name: 'Gmail', email: 'user@gmail.com', incomingHost: 'imap.gmail.com', outgoingHost: 'smtp.gmail.com', password: 'app-password', userName: 'John Doe', ); ``` -------------------------------- ### Start IMAP IDLE Mode Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Initiates IMAP IDLE mode, enabling real-time notifications for new messages or changes. Events are streamed via an event bus. ```dart Future idleStart() ``` -------------------------------- ### Connect to IMAP Server Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/lowlevelclients.md Establishes a connection to an IMAP server. Supports both secure (SSL/TLS) and plain connections. Throws ImapException on failure. ```dart Future connectToServer( String host, int port, { bool isSecure = true, } ) ``` ```dart final client = ImapClient(isLogEnabled: true); await client.connectToServer('imap.gmail.com', 993); ``` -------------------------------- ### Send Email with MessageBuilder Source: https://github.com/enough-software/enough_mail/blob/main/_autodocs/INDEX.md Demonstrates constructing a multipart alternative email with plain text and HTML content, setting sender, recipients, and subject, then sending it. ```dart final message = MessageBuilder.prepareMultipartAlternativeMessage( plainText: 'Hello World', htmlText: '

Hello World

', ) ..from = [MailAddress('John Doe', 'john@example.com')] ..to = [MailAddress('Jane Doe', 'jane@example.com')] ..subject = 'Greeting'; final mimeMessage = message.buildMimeMessage(); await client.sendMessage(mimeMessage); ```