### SMTPSender Examples Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/sender.md Demonstrates creating an SMTPSender with and without authentication. ```go // Without authentication sender := enmime.NewSMTP("localhost:25", nil) // With authentication auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com") sender := enmime.NewSMTP("mail.example.com:587", auth) ``` -------------------------------- ### PartMatcher Usage Example Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/types.md Demonstrates how to use a PartMatcher with BreadthMatchAll to find all plain text parts. ```go matcher := func(p *Part) bool { return p.ContentType == "text/plain" } attachments := root.BreadthMatchAll(matcher) ``` -------------------------------- ### Example: Convert Part Tree to Envelope Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/envelope.md This example demonstrates how to read MIME parts from a reader and then convert the resulting Part tree into an Envelope using EnvelopeFromPart. Error handling is omitted for brevity. ```go parts, _ := enmime.ReadParts(reader) env, err := enmime.EnvelopeFromPart(parts) ``` -------------------------------- ### Import enmime Package Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Import the enmime package to start using its functionalities. ```go import "github.com/jhillyerd/enmime/v2" ``` -------------------------------- ### Simple Parsing Example Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Demonstrates basic message parsing using ReadEnvelope and accessing the plain text content. ```go env, err := enmime.ReadEnvelope(reader) fmt.Println(env.Text) ``` -------------------------------- ### Parse and Forward Email Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md This example demonstrates how to read an email from a file, modify its headers, and then forward it using an SMTP client. Ensure you have an 'email.eml' file and an SMTP server running on localhost:25. ```Go package main import ( "bytes" "log" "net/smtp" "os" "github.com/jhillyerd/enmime/v2" ) func main() { // Read email file, _ := os.Open("email.eml") env, _ := enmime.ReadEnvelope(file) // Modify env.SetHeader("X-Forwarded-For", []string{"user@example.com"}) // Re-send sender := enmime.NewSMTP("localhost:25", nil) var buf bytes.Buffer env.Root.Encode(&buf) newFrom := "forwarder@example.com" newRecipients := []string{"recipient@example.com"} err := sender.Send(newFrom, newRecipients, buf.Bytes()) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create a new MailBuilder Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/mailbuilder.md Use the Builder function to get an initialized MailBuilder struct. This is the starting point for constructing a MIME message. ```go builder := enmime.Builder() ``` -------------------------------- ### Example Usage of ReadEnvelope Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/envelope.md Demonstrates how to read an email from a file, parse it into an Envelope, and access its plain text and attachment count. Ensure the email file exists at the specified path. ```go file, _ := os.Open("email.eml") defer file.Close() env, err := enmime.ReadEnvelope(file) if err != nil { log.Fatal(err) } fmt.Println(env.Text) fmt.Println(len(env.Attachments)) ``` -------------------------------- ### Configure Custom Email Parser Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/INDEX.md Create a custom parser instance, for example, to skip malformed parts during parsing. ```go parser := enmime.NewParser( enmime.SkipMalformedParts(true), ) env, err := parser.ReadEnvelope(reader) ``` -------------------------------- ### Build a Complete MIME Message Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/toplevelfunctions.md Construct a full MIME message by chaining builder methods. This example demonstrates setting sender, recipients, subject, text and HTML bodies, and adding file attachments. The message is then encoded into bytes for sending. ```go message, err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). CC("", "cc@example.com"). Subject("Test Message"). Text([]byte("Plain text body")). HTML([]byte("
HTML body")). AddFileAttachment("/path/to/document.pdf"). Build() if err != nil { log.Fatal(err) } // Encode to bytes for sending var buf bytes.Buffer message.Encode(&buf) fmt.Println(buf.String()) ``` -------------------------------- ### Create a New MailBuilder Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/toplevelfunctions.md Use the Builder() function to get an empty MailBuilder struct. This is the starting point for constructing MIME messages using a fluent interface. ```go func Builder() MailBuilder ``` -------------------------------- ### SMTPSender Send Method Example Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/sender.md Sends an email using the SMTPSender. Handles potential errors during transmission. ```go sender := enmime.NewSMTP("mail.example.com:25", nil) err := sender.Send( "bounce@example.com", []string{"recipient@example.com"}, messageBytes, ) if err != nil { log.Printf("Failed to send email: %v", err) } ``` -------------------------------- ### Using SimpleErrorCollector with ReadHeader Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Example demonstrating how to instantiate and use a SimpleErrorCollector with the ReadHeader function to capture parsing issues. ```go // Use with ReadHeader collector := &SimpleErrorCollector{} header, err := enmime.ReadHeader(reader, collector) for _, w := range collector.Warnings { fmt.Printf("Warning: %s\n", w) } ``` -------------------------------- ### Match Any Image Content Type Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use this matcher to identify any email part where the Content-Type starts with 'image/'. ```go func(p *Part) bool { return strings.HasPrefix(p.ContentType, "image/") } ``` -------------------------------- ### Match Multipart Content Type Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use this matcher to identify any email part where the Content-Type starts with 'multipart/'. ```go func(p *Part) bool { return strings.HasPrefix(p.ContentType, "multipart/") } ``` -------------------------------- ### Match Any Text Content Type Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use this matcher to identify any email part where the Content-Type starts with 'text/'. ```go func(p *Part) bool { return strings.HasPrefix(p.ContentType, "text/") } ``` -------------------------------- ### Error Plain Text From HTML Example Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/errors.md Illustrates a scenario where enmime generates a plain text version from HTML content when no text/plain part is available. ```Go ErrorPlainTextFromHTML ``` -------------------------------- ### Get All Header Keys Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/envelope.md Retrieves a list of all header keys present in the email message. Useful for iterating through all available headers. ```go keys := env.GetHeaderKeys() for _, key := range keys { fmt.Printf("Header: %s\n", key) } ``` -------------------------------- ### Get Raw Part Content Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/types.md Use RawContent to prevent automatic decoding of Content-Transfer-Encoding and return raw part content. The default is false. ```go func RawContent(a bool) Option ``` -------------------------------- ### Check if Header Contains Addresses Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Example demonstrating how to check if a header contains email addresses using the AddressHeaders map and parse them. ```go if enmime.AddressHeaders[strings.ToLower(headerName)] { addrs, err := enmime.ParseAddressList(headerValue) // Process addresses } ``` -------------------------------- ### Get All Header Values Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/envelope.md Retrieves all values for a given header, decoding RFC 2047 encoded words into UTF-8 strings. Ideal for headers that can contain multiple entries, like 'Received'. ```go receivedHeaders := env.GetHeaderValues("Received") ``` -------------------------------- ### Create a New Parser with Options Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/parser.md Instantiates a new Parser with custom configurations using Option functions. Default configuration is applied if no options are provided. ```go parser := enmime.NewParser( enmime.SkipMalformedParts(true), enmime.MaxStoredPartErrors(10), ) ``` -------------------------------- ### Build and Run mime-dump Source: https://github.com/jhillyerd/enmime/blob/main/cmd/mime-dump/README.md Build the mime-dump utility using 'go build' and then execute it, passing an email file as an argument to parse and display its structure. ```bash go build ``` ```bash ./mime-dump ../test-data/mail/html-mime-inline.raw ``` -------------------------------- ### Build and Send Email via SMTP Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/toplevelfunctions.md Constructs a new email with specified recipients, subject, and text content, then sends it using an SMTP client. Configure the SMTP server address and port correctly. ```Go sender := enmime.NewSMTP("localhost:25", nil) err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("Test message")), Send(sender) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Available enmime builder methods Source: https://github.com/jhillyerd/enmime/wiki/Builder-Usage List of available methods for configuring email content, headers, and attachments. ```go AddAttachment(b []byte, contentType string, fileName string) AddFileAttachment(path string) AddFileInline(path string) AddInline(b []byte, contentType string, fileName string, contentID string) BCC(name, addr string) BCCAddrs(bcc []mail.Address) CC(name, addr string) CCAddrs(cc []mail.Address) Date(date time.Time) From(name, addr string) HTML(body []byte) Header(name, value string) ReplyTo(name, addr string) Subject(subject string) Text(body []byte) To(name, addr string) ToAddrs(to []mail.Address) ``` -------------------------------- ### Build Simple Email Message Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Shows how to construct a basic email message with sender, recipient, subject, and text body using the enmime builder. ```Go msg, err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("Body")). Build() ``` -------------------------------- ### Legacy System Support Configuration Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/configuration.md Configure the parser and encoder for legacy system support. This uses a custom parser for non-standard headers and encodes with quoted-printable. ```go parser := enmime.NewParser( enmime.SetCustomParseMediaType(legacyMediaTypeParser), ) encoder := enmime.NewEncoder( enmime.ForceQuotedPrintableCte(true), ) // Uses custom parser for non-standard headers, encodes with quoted-printable ``` -------------------------------- ### Build and Send an Email Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/README.md Constructs a MIME email message using a fluent interface and sends it via SMTP. Use this for programmatically creating and dispatching emails. ```go sender := enmime.NewSMTP("localhost:25", nil) err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("Test")). Send(sender) ``` -------------------------------- ### Using Header Parsing with Envelope and Part Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Demonstrates how Enmime's header parsing functions are used internally by Envelope and Part types. ```go // Envelope.GetHeader uses ParseAddressList internally toAddresses, err := env.AddressList("To") ``` ```go // Envelope.GetHeader returns RFC 2047 decoded headers subject := env.GetHeader("Subject") ``` ```go // Part headers are read using ReadHeader part.setupHeaders(reader, defaultContentType) ``` -------------------------------- ### Get MailBuilder Error Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/mailbuilder.md Retrieves any stored error encountered during file attachment or inline reading. Returns nil if no error occurred. ```go func (p MailBuilder) Error() error ``` -------------------------------- ### Send Email via SMTP Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Demonstrates sending a constructed email message using an SMTP client. ```Go sender := enmime.NewSMTP("mail.example.com:25", auth) err := builder.Send(sender) ``` -------------------------------- ### Build Message with Attachments Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Illustrates adding file attachments to an email message during the build process. ```Go msg, err := enmime.Builder(). From(...).To(...).Subject(...). Text(...). AddFileAttachment("/path/file.pdf"). Build() ``` -------------------------------- ### Create New Part Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/part.md Creates a new Part object with the specified content type. Use this to initialize a new email part. ```go textPart := enmime.NewPart("text/plain") textPart.Content = []byte("Hello, world!") htmlPart := enmime.NewPart("text/html") htmlPart.Content = []byte("...") ``` -------------------------------- ### Parse an Email Message Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/README.md Reads a MIME message from a reader and extracts envelope information. Use this to quickly get the subject and text body of an email. ```go env, err := enmime.ReadEnvelope(reader) if err != nil { log.Fatal(err) } fmt.Println("Subject:", env.GetHeader("Subject")) fmt.Println("Body:", env.Text) ``` -------------------------------- ### Construct and send a message with enmime Source: https://github.com/jhillyerd/enmime/wiki/Builder-Usage Use the fluent builder to define message components and send via SMTP. ```go msg := enmime.Builder(). From("Alice", "alice@inbucket.org"). Subject("Greetings!"). Text([]byte("Hi Bob!")). To("Bob", "bob@inbucket.org") err := msg.Send(smtpHost, smtpAuth) ``` -------------------------------- ### Custom Email Parsing Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Demonstrates how to create a custom parser with specific options like skipping malformed parts and disabling text conversion. ```Go parser := enmime.NewParser( enmime.SkipMalformedParts(true), enmime.DisableTextConversion(true), ) env, err := parser.ReadEnvelope(reader) ``` -------------------------------- ### Find Inline Images in Email Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use BreadthMatchAll to find parts with Disposition 'inline' and ContentType starting with 'image/'. This helps in identifying and processing images embedded within the email body. ```go env, _ := enmime.ReadEnvelope(reader) images := env.Root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == "inline" && strings.HasPrefix(p.ContentType, "image/") }) for _, img := range images { fmt.Printf("Image: %s (CID: %s)\n", img.FileName, img.ContentID) } ``` -------------------------------- ### NewParser Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Creates a new configured Parser instance with optional configuration options. ```APIDOC ## NewParser ### Description Creates a new configured Parser instance with optional configuration options. ### Function Signature `NewParser(...Option) *Parser` ### Parameters #### Query Parameters - `...Option` (type: ...Option) - Optional - Configuration options for the parser. ### Returns - `*Parser`: A pointer to the newly created Parser object. ``` -------------------------------- ### Configure and Use Custom Parser Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Create a custom enmime parser with specific configurations like skipping malformed parts, disabling text conversion, or setting a limit on stored part errors. Then use this parser to read envelopes or parts. ```go parser := enmime.NewParser( enmime.SkipMalformedParts(true), enmime.DisableTextConversion(true), enmime.MaxStoredPartErrors(10), ) env, err := parser.ReadEnvelope(reader) root, err := parser.ReadParts(reader) env, err := parser.EnvelopeFromPart(root) ``` -------------------------------- ### Get Specific Header Value Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/envelope.md Retrieves a single header's value, decoding RFC 2047 encoded words into a UTF-8 string. Use for headers expected to have one value. ```go subject := env.GetHeader("Subject") from := env.GetHeader("From") ``` -------------------------------- ### Build an Email Message Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/INDEX.md Construct a new email message with sender, recipient, subject, and body using the enmime builder. ```go msg, err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("Body")). Build() ``` -------------------------------- ### Complex Matching for Email Parts Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/matching.md Combine multiple criteria to precisely select email parts. Examples include finding image attachments, text body parts, problematic parts with errors, or large attachments. ```go // Image attachments imageAttachments := root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == "attachment" && strings.HasPrefix(p.ContentType, "image/") }) // Text body parts (not attachments) bodyText := root.BreadthMatchAll(func(p *Part) bool { return (p.ContentType == "text/plain" || p.ContentType == "text/html") && p.Disposition != "attachment" }) // Unread parts (those with errors) problematicParts := root.BreadthMatchAll(func(p *Part) bool { return len(p.Errors) > 0 }) // Large attachments largeFiles := root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == "attachment" && len(p.Content) > 1_000_000 }) ``` -------------------------------- ### Set From Address Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/mailbuilder.md Sets the From header with a display name and email address. Use this when initializing or updating the sender's information. ```go builder = builder.From("John Doe", "john@example.com") ``` -------------------------------- ### enmime Type Aliases for Headers Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Commonly used string constants for address headers. ```go // Address headers map envelope.AddressHeaders["to"] envelope.AddressHeaders["cc"] envelope.AddressHeaders["bcc"] envelope.AddressHeaders["from"] envelope.AddressHeaders["reply-to"] // ... and others ``` -------------------------------- ### Create New SMTPSender Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/sender.md Constructs a new SMTPSender. Authentication is optional. ```go func NewSMTP(addr string, auth smtp.Auth) *SMTPSender ``` -------------------------------- ### Organizing Email Parts with Envelope Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/matching.md Demonstrates how the Envelope type uses matching functions to automatically organize email parts such as attachments, inlines, and other multipart content. These are populated using BreadthMatchAll with specific matchers. ```Go env, _ := enmime.ReadEnvelope(reader) // These are populated using BreadthMatchAll with specific matchers fmt.Println("Attachments:", len(env.Attachments)) // p.Disposition == "attachment" fmt.Println("Inlines:", len(env.Inlines)) // p.Disposition == "inline" fmt.Println("OtherParts:", len(env.OtherParts)) // Other multipart content ``` -------------------------------- ### Configuration Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Options for configuring the parser and encoder. ```APIDOC ## NewParser ### Description Creates a new Parser instance with optional configuration options. ### Method Go Function ### Signature `func NewParser(options ...ParserOption) *Parser` ### Parameters - **options** (...ParserOption) - A variadic list of ParserOption functions to configure the parser. ### Example Options - `SkipMalformedParts` - `MultipartWOBoundaryAsSinglePart` - `MaxStoredPartErrors` - `RawContent` ``` ```APIDOC ## NewEncoder ### Description Creates a new Encoder instance with optional configuration options. ### Method Go Function ### Signature `func NewEncoder(options ...EncoderOption) *Encoder` ### Parameters - **options** (...EncoderOption) - A variadic list of EncoderOption functions to configure the encoder. ### Example Options - `MaxLineLength` - `WriteBoundary` ``` -------------------------------- ### Configure Custom MIME Parser Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/README.md Creates a custom MIME parser with specific configurations, such as skipping malformed parts or disabling text conversion. Use this to tailor parsing behavior. ```go parser := enmime.NewParser( enmime.SkipMalformedParts(true), enmime.DisableTextConversion(true), ) env, err := parser.ReadEnvelope(reader) ``` -------------------------------- ### From Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/mailbuilder.md Sets the From header with a display name and email address for the sender. ```APIDOC ## From ### Description Sets the From header with a name and email address. ### Method MailBuilder.From ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Optional - Display name for the sender - **addr** (string) - Required - Email address of the sender ### Returns MailBuilder — copy with From header set ### Example ```go builder = builder.From("John Doe", "john@example.com") ``` ``` -------------------------------- ### Build Basic Email Message Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Construct a basic MIME message using the enmime.Builder. Specify sender, recipient, subject, and plain text content. ```go msg, err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("Plain text body")), Build() // Returns: *Part (root of MIME tree) ``` -------------------------------- ### Match Email Parts by Filename Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/matching.md Select parts by their FileName attribute. Supports exact matches, suffix checks, or simply checking for the presence of a filename. ```go // Parts with specific filename document := root.BreadthMatchFirst(func(p *Part) bool { return p.FileName == "report.pdf" }) // Parts matching filename pattern pdfFiles := root.BreadthMatchAll(func(p *Part) bool { return strings.HasSuffix(p.FileName, ".pdf") }) // Parts with any filename withFilename := root.BreadthMatchAll(func(p *Part) bool { return p.FileName != "" }) ``` -------------------------------- ### Send Email with MailBuilder and SMTPSender Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/sender.md Builds and sends an email using MailBuilder and an SMTPSender. ```go // Build and send a message sender := enmime.NewSMTP("localhost:25", nil) err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Hello"). Text([]byte("This is a test email")), Send(sender) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Standard Header Parameters Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Constants for standard MIME header parameter names extracted from headers like Content-Type. ```go const ( hpBoundary = "boundary" hpCharset = "charset" hpFile = "file" hpFilename = "filename" hpName = "name" hpModDate = "modification-date" ) ``` -------------------------------- ### enmime Type Aliases for Dispositions Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Commonly used string constants for content disposition types. ```go // Dispositions envelope.cdAttachment // "attachment" envelope.cdInline // "inline" ``` -------------------------------- ### Build Email Message with Attachments Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Construct a MIME message with file attachments. Supports adding attachments by byte slice or by file path. ```go msg, err := enmime.Builder(). From("sender@example.com", "sender@example.com"). To("", "recipient@example.com"). Subject("Report"). Text([]byte("See attached")), AddAttachment(pdfBytes, "application/pdf", "report.pdf"). AddFileAttachment("/path/to/image.png"), Build() ``` -------------------------------- ### Search Message Parts by Content Type Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/MANIFEST.txt Shows how to find specific parts within an email message, such as all image parts, using a breadth-first search. ```Go images := root.BreadthMatchAll(func(p *Part) bool { return strings.HasPrefix(p.ContentType, "image/") }) ``` -------------------------------- ### Handling Non-indented Header Continuations Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Shows how Enmime repairs header values that continue on a new line without indentation. ```go Subject: This is a long header value without indentation ^ non-indented continuation is repaired with warning ``` -------------------------------- ### Preserve Original Format Configuration Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/README.md Configure the enmime parser to preserve the raw content, disable text conversion, and disable character detection. ```go parser := enmime.NewParser( enmime.RawContent(true), enmime.DisableTextConversion(true), enmime.DisableCharacterDetection(true), ) ``` -------------------------------- ### Handling Space Before Colon in Headers Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/header.md Demonstrates how Enmime repairs headers with a space before the colon separator. ```go X-Custom : value ^ space before colon is repaired ``` -------------------------------- ### Implement Custom Sender Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/sender.md Provides a template for creating a custom Sender implementation for non-SMTP transports. ```go type CustomSender struct { // Your fields } func (c *CustomSender) Send(reversePath string, recipients []string, msg []byte) error { // Your implementation return nil } // Use it with MailBuilder builder := enmime.Builder() // ... configure builder ... customSender := &CustomSender{} err := builder.Send(customSender) ``` -------------------------------- ### Build Email Message for Testing Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use the enmime.Builder to construct an email message programmatically. Setting RandSeed ensures reproducible boundary generation for consistent testing. ```go // Reproducible boundary generation msg, _ := enmime.Builder(). RandSeed(12345). From("test@example.com", "test@example.com"). To("", "recipient@example.com"). Subject("Test"). Text([]byte("Test body")). Build() // Encode and verify var buf bytes.Buffer msg.Encode(&buf) output := buf.String() // Consistent output due to RandSeed ``` -------------------------------- ### Configure Parser Minimum Charset Detection Runes Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/configuration.md Sets the minimum number of runes before charset detection is attempted. Adjust detection sensitivity; higher values reduce false detection on short text, lower values enable detection on brief messages. ```Go parser := enmime.NewParser( enmime.MinCharsetDetectRunes(50), // Enable detection on text > 50 runes ) ``` -------------------------------- ### Create a Lenient Custom Parser Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/api-reference/toplevelfunctions.md Instantiate a custom enmime Parser with options for lenient parsing, such as skipping malformed parts and treating multipart messages without a boundary as a single part. This parser can then be used to read email envelopes. ```go // Lenient parsing parser := enmime.NewParser( enmime.SkipMalformedParts(true), enmime.MultipartWOBoundaryAsSinglePart(true), ) env, err := parser.ReadEnvelope(reader) ``` -------------------------------- ### Match Specific Content-ID Source: https://github.com/jhillyerd/enmime/blob/main/_autodocs/QUICK-REFERENCE.md Use this matcher to identify email parts with the specific Content-ID '