common

package
v0.6.0-beta.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 4, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package common provides utility functions and structures used across the gomail project.

Overview

The common package includes essential utilities such as email validation, sanitization, MIME type determination, and structures for handling email messages and attachments. These utilities are crucial for ensuring the integrity and security of email handling within the gomail project.

Components

  • EmailMessage: Struct for constructing and manipulating email messages.
  • Attachment: Struct for managing email attachments, including file handling and base64 encoding.
  • Validation: Functions for validating email addresses and slices of email addresses.
  • Sanitization: Functions for sanitizing input to prevent injection attacks.

Usage

The functions and structs in this package are used internally by other packages in the gomail project but can also be used directly if needed.

Example:

package main

import (
    "github.com/darkrockmountain/gomail/common"
)

func main() {
    email := common.NewEmailMessage("sender@example.com", []string{"recipient@example.com"}, "Subject", "Email body")
    fmt.Println(email.GetSubject())
}

For detailed information on each function and struct, refer to their respective documentation within this package.

Index

Examples

Constants

View Source
const DefaultMaxAttachmentSize = 25 * 1024 * 1024 // 25 MB

Variables

This section is empty.

Functions

func BuildMimeMessage

func BuildMimeMessage(message *EmailMessage) ([]byte, error)

BuildMimeMessage constructs the MIME message for the email, including text, HTML, and attachments. This function builds a multipart MIME message based on the provided email message. It supports plain text, HTML content, and multiple attachments.

Parameters:

  • message: A pointer to an EmailMessage struct containing the details of the email to be sent.

Returns:

  • []byte: A byte slice containing the complete MIME message.
  • error: An error if constructing the MIME message fails, otherwise nil.

Example:

message := gomail.NewEmailMessage(
	"sender@example.com",
	[]string["recipient@example.com"],
	"Test Email",
	"This is a test email.",)
	.SetHtml("<p>This is a test email.</p>").AddAttachment(Attachment{
	Filename: "test.txt",
	Content:  []byte("This is a test attachment."),
})
mimeMessage, err := BuildMimeMessage(message)
if err != nil {
    log.Fatalf("Failed to build MIME message: %v", err)
}
fmt.Println(string(mimeMessage))

func GetMimeType

func GetMimeType(filename string) string

GetMimeType returns the MIME type based on the file extension. This function takes a filename, extracts its extension, and returns the corresponding MIME type.

Parameters:

  • filename: A string containing the name of the file whose MIME type is to be determined.

Returns:

  • string: The MIME type corresponding to the file extension.

Example:

mimeType := GetMimeType("document.pdf")
fmt.Println(mimeType)
//Output: application/pdf
Example
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	filename := "document.pdf"
	mimeType := common.GetMimeType(filename)
	fmt.Println(mimeType)
}
Output:

application/pdf

func IsHTML

func IsHTML(str string) bool

IsHTML checks if a string contains HTML tags.

Parameters:

  • str: The string to check.

Returns:

  • bool: True if the string contains HTML tags, otherwise false.
Example (False)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	plainText := "Just a plain text"
	result := common.IsHTML(plainText)
	fmt.Println(result)
}
Output:

false
Example (PartiallyContainsHtml)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	combined := "Plain text with <html> tag"
	result := common.IsHTML(combined)
	fmt.Println(result)
}
Output:

true
Example (True)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	html := "<html><body>HTML body</body></html>"
	result := common.IsHTML(html)
	fmt.Println(result)
}
Output:

true

func StrPtr

func StrPtr(str string) *string

StrPtr takes a string value and returns a pointer to that string. This function is useful when you need to work with string pointers, such as in scenarios where you need to pass a string by reference or handle optional string fields.

Parameters:

  • str (string): The input string value that you want to convert to a pointer.

Returns:

  • *string: A pointer to the input string value.

Example:

name := "John Doe"
namePtr := StrPtr(name)
fmt.Println(namePtr)  // Output: memory address of the string
fmt.Println(*namePtr) // Output: "John Doe"

Detailed explanation: The StrPtr function creates a pointer to the given string `str`. This can be particularly useful in the following scenarios:

  1. Passing strings by reference to functions, which can help avoid copying large strings.
  2. Working with data structures that use pointers to represent optional fields or nullable strings.
  3. Interfacing with APIs or libraries that require or return string pointers.

By using this function, you can easily obtain a pointer to a string and utilize it in contexts where pointers are needed, thus enhancing flexibility and efficiency in your Go programs.

Example
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	name := "John Doe"
	namePtr := common.StrPtr(name)
	fmt.Println(*namePtr)
}
Output:

John Doe

func ValidateEmail

func ValidateEmail(email string) string

ValidateEmail trims the email and checks if it is a valid email address. Returns the trimmed email if valid, otherwise returns an empty string.

Example
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	email := "test@example.com"
	result := common.ValidateEmail(email)
	fmt.Println(result)
}
Output:

test@example.com
Example (Not)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	email := "test@com"
	result := common.ValidateEmail(email)
	fmt.Println(result)
}
Output:

Example (Trim)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	email := "  test@example.com  "
	result := common.ValidateEmail(email)
	fmt.Println(result)
}
Output:

test@example.com

func ValidateEmailSlice

func ValidateEmailSlice(emails []string) []string

ValidateEmailSlice trims and validates each email in the slice. Returns a slice of trimmed valid emails, excluding any invalid emails.

Example
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	emails := []string{"test@example.com", "test@domain_name.com"}
	result := common.ValidateEmailSlice(emails)
	fmt.Println(result)
}
Output:

[test@example.com test@domain_name.com]
Example (Partial)
package main

import (
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {
	emails := []string{"test@example.com", "test@com"}
	result := common.ValidateEmailSlice(emails)
	fmt.Println(result)
}
Output:

[test@example.com]

Types

type Attachment

type Attachment struct {
	// contains filtered or unexported fields
}

Attachment represents an email attachment with its filename and content. Use this struct to specify files to be attached to the email.

Example:

To marshal an Attachment to JSON:

attachment := common.NewAttachment("document.pdf", []byte("file content"))
jsonData, err := json.Marshal(attachment)
if err != nil {
    fmt.Println("Error marshaling to JSON:", err)
    return
}
fmt.Println("JSON output:", string(jsonData))

To unmarshal an Attachment from JSON:

jsonData := `{
    "filename": "file.txt",
    "content": "ZmlsZSBjb250ZW50" // base64 encoded "file content"
}`
var attachment common.Attachment
err := json.Unmarshal([]byte(jsonData), &attachment)
if err != nil {
    fmt.Println("Error unmarshaling from JSON:", err)
    return
}
fmt.Printf("Unmarshaled Attachment: %+v\n", attachment)

func NewAttachment

func NewAttachment(filename string, content []byte) *Attachment

NewAttachment creates a new Attachment instance with the specified filename and content. It initializes the private fields of the Attachment struct with the provided values.

Example:

content := []byte("file content")
attachment := NewAttachment("document.pdf", content)
fmt.Println(attachment.GetFilename()) // Output: document.pdf
fmt.Println(string(attachment.GetContent())) // Output: file content

func NewAttachmentFromFile

func NewAttachmentFromFile(filePath string) (*Attachment, error)

NewAttachmentFromFile creates a new Attachment instance from the specified file path. It reads the content of the file and initializes the private fields of the Attachment struct.

Example:

attachment, err := NewAttachmentFromFile("path/to/document.pdf")
if err != nil {
    fmt.Println("Error creating attachment:", err)
    return
}
fmt.Println(attachment.GetFilename()) // Output: document.pdf
fmt.Println(string(attachment.GetContent())) // Output: (file content)

func (*Attachment) GetBase64Content

func (a *Attachment) GetBase64Content() []byte

GetBase64Content returns the content of the attachment as a base64-encoded byte slice. If the attachment is nil, it returns an empty byte slice.

Returns:

  • []byte: The base64-encoded content of the attachment as a byte slice. Returns an empty byte slice if the attachment is nil.

func (*Attachment) GetBase64StringContent

func (a *Attachment) GetBase64StringContent() string

GetBase64StringContent returns the content of the attachment as a base64-encoded string. If the attachment is nil, it returns an empty string.

Returns:

  • string: The base64-encoded content of the attachment as a string. Returns an empty string if the attachment is nil.

func (*Attachment) GetFilename

func (a *Attachment) GetFilename() string

GetFilename safely returns the filename of the attachment. It uses the default text sanitizer to escape special characters and trim whitespace. If the attachment is nil, it returns an empty string.

Returns:

  • string: The sanitized filename.

func (*Attachment) GetRawContent

func (a *Attachment) GetRawContent() []byte

GetRawContent returns the content of the attachment as its raw byte slice. If the attachment is nil, it returns an empty byte slice.

Returns:

  • []byte: The content of the attachment as a byte slice. Returns an empty byte slice if the attachment is nil.

func (Attachment) MarshalJSON

func (a Attachment) MarshalJSON() ([]byte, error)

MarshalJSON custom marshaler for Attachment This method converts the Attachment struct into a JSON representation. It creates an anonymous struct with exported fields and JSON tags, copies the values from the private fields, and then marshals it to JSON.

Example:

attachment := Attachment{
    filename: "file.txt",
    content:  []byte("file content"),
}
jsonData, err := json.Marshal(attachment)
if err != nil {
    fmt.Println("Error marshaling to JSON:", err)
    return
}
fmt.Println("JSON output:", string(jsonData))

func (*Attachment) SetContent

func (a *Attachment) SetContent(content []byte)

SetContent sets the content of the attachment. It assigns the provided content to the private content field.

Example:

var attachment Attachment
content := []byte("file content")
attachment.SetContent(content)
fmt.Println(string(attachment.GetContent())) // Output: file content

func (*Attachment) SetFilename

func (a *Attachment) SetFilename(filename string)

SetFilename sets the filename of the attachment. It assigns the provided filename to the private filename field.

Example:

var attachment Attachment
attachment.SetFilename("document.pdf")
fmt.Println(attachment.GetFilename()) // Output: document.pdf

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler for Attachment This method converts a JSON representation into an Attachment struct. It creates an anonymous struct with exported fields and JSON tags, unmarshals the JSON data into this struct, and then copies the values to the private fields of the Attachment struct.

Example:

jsonData := `{
    "filename": "file.txt",
    "content": "ZmlsZSBjb250ZW50" // base64 encoded "file content"
}`
var attachment Attachment
err := json.Unmarshal([]byte(jsonData), &attachment)
if err != nil {
    fmt.Println("Error unmarshaling from JSON:", err)
    return
}
fmt.Printf("Unmarshaled Attachment: %+v\n", attachment)

type EmailMessage

type EmailMessage struct {
	// contains filtered or unexported fields
}

EmailMessage contains the fields for sending an email. Use this struct to specify the sender, recipient, subject, and content of the email, as well as any attachments. This struct also supports custom sanitizers for text and HTML content to ensure that email content is safe and sanitized according to specific requirements.

Example:

To marshal an EmailMessage to JSON:

email := common.NewFullEmailMessage(
    "sender@example.com",
    []string{"recipient@example.com"},
    "Subject",
    []string{"cc@example.com"},
    []string{"bcc@example.com"},
    "replyto@example.com",
    "This is the email content.",
    "<p>This is the email content.</p>",
    []common.Attachment{*common.NewAttachment("attachment1.txt", []byte("file content"))})

jsonData, err := json.Marshal(email)
if err != nil {
    fmt.Println("Error marshaling to JSON:", err)
    return
}
fmt.Println("JSON output:", string(jsonData))

To unmarshal an EmailMessage from JSON:

jsonData := `{
    "from": "sender@example.com",
    "to": ["recipient@example.com"],
    "cc": ["cc@example.com"],
    "bcc": ["bcc@example.com"],
    "replyTo": "replyto@example.com",
    "subject": "Subject",
    "text": "This is the email content.",
    "html": "<p>This is the email content.</p>",
    "attachments": [{"filename": "attachment1.txt", "content": "ZmlsZSBjb250ZW50"}] // base64 encoded "file content"
}`
var email common.EmailMessage
err := json.Unmarshal([]byte(jsonData), &email)
if err != nil {
    fmt.Println("Error unmarshaling from JSON:", err)
    return
}
fmt.Printf("Unmarshaled EmailMessage: %+v\n", email)

func NewEmailMessage

func NewEmailMessage(from string, to []string, subject string, body string) *EmailMessage

NewEmailMessage creates a new EmailMessage with the required fields. If the body contains HTML tags, it sets the HTML field; otherwise, it sets the Text field.

Parameters:

  • from: The sender email address.
  • to: A slice of recipient email addresses.
  • subject: The email subject.
  • body: The content of the email, which can be plain text or HTML.

Returns:

  • *EmailMessage: A pointer to the newly created EmailMessage struct.

func NewFullEmailMessage

func NewFullEmailMessage(from string, to []string, subject string, cc []string, bcc []string, replyTo string, textBody string, htmlBody string, attachments []Attachment) *EmailMessage

NewFullEmailMessage creates a new EmailMessage with all fields.

Parameters:

  • from: The sender email address.
  • to: A slice of recipient email addresses.
  • subject: The email subject.
  • cc: A slice of CC recipient email addresses (optional).
  • bcc: A slice of BCC recipient email addresses (optional).
  • replyTo: The reply-to email address (optional).
  • textBody: The plain text content of the email.
  • htmlBody: The HTML content of the email (optional).
  • attachments: A slice of attachments (optional).

Returns:

  • *EmailMessage: A pointer to the newly created EmailMessage struct.

func (*EmailMessage) AddAttachment

func (e *EmailMessage) AddAttachment(attachment Attachment) *EmailMessage

AddAttachment adds an attachment to the email.

Parameters:

  • attachment: An Attachment struct representing the file to be attached.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) AddBCCRecipient

func (e *EmailMessage) AddBCCRecipient(recipient string) *EmailMessage

AddBCCRecipient adds a recipient email address to the BCC field.

Parameters:

  • recipient: A recipient email address to be added.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) AddCCRecipient

func (e *EmailMessage) AddCCRecipient(recipient string) *EmailMessage

AddCCRecipient adds a recipient email address to the CC field.

Parameters:

  • recipient: A recipient email address to be added.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) AddToRecipient

func (e *EmailMessage) AddToRecipient(recipient string) *EmailMessage

AddToRecipient adds a recipient email address to the To field.

Parameters:

  • recipient: A recipient email address to be added.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) GetAttachments

func (e *EmailMessage) GetAttachments() []Attachment

GetAttachments returns the attachments to be included in the email, filtering out those that exceed the maximum size. If the EmailMessage is nil, it returns an empty slice.

Returns:

  • []Attachment: The attachments to be included in the email.

func (*EmailMessage) GetBCC

func (e *EmailMessage) GetBCC() []string

GetBCC returns a slice of trimmed and validated BCC recipient email addresses. Excludes any invalid email addresses.

Returns:

  • []string: The validated BCC recipient email addresses.

func (*EmailMessage) GetCC

func (e *EmailMessage) GetCC() []string

GetCC returns a slice of trimmed and validated CC recipient email addresses. Excludes any invalid email addresses.

Returns:

  • []string: The validated CC recipient email addresses.

func (*EmailMessage) GetFrom

func (e *EmailMessage) GetFrom() string

GetFrom returns the trimmed and validated sender email address. Returns an empty string if the email is invalid.

Returns:

  • string: The validated sender email address.

func (*EmailMessage) GetHTML

func (e *EmailMessage) GetHTML() string

GetHTML returns the sanitized HTML content of the email. It uses the custom html sanitizer if set, otherwise the default sanitizer.

Returns:

  • string: The sanitized HTML content of the email.

func (*EmailMessage) GetReplyTo

func (e *EmailMessage) GetReplyTo() string

GetReplyTo returns the trimmed and validated reply-to email address. Returns an empty string if the email is invalid.

Returns:

  • string: The validated reply-to email address.

func (*EmailMessage) GetSubject

func (e *EmailMessage) GetSubject() string

GetSubject returns the sanitized email subject. It uses the custom text sanitizer if set, otherwise the default text sanitizer to escape special characters and trim whitespace. If the EmailMessage is nil, it returns an empty string.

Returns:

  • string: The sanitized email subject.

func (*EmailMessage) GetText

func (e *EmailMessage) GetText() string

GetText returns the sanitized plain text content of the email. It uses the custom text sanitizer if set, otherwise the default sanitizer.

Returns:

  • string: The sanitized plain text content of the email.

func (*EmailMessage) GetTo

func (e *EmailMessage) GetTo() []string

GetTo returns a slice of trimmed and validated recipient email addresses. Excludes any invalid email addresses.

Returns:

  • []string: The validated recipient email addresses.

func (*EmailMessage) MarshalJSON

func (e *EmailMessage) MarshalJSON() ([]byte, error)

MarshalJSON custom marshaler for EmailMessage This method converts the EmailMessage struct into a JSON representation. It creates an anonymous struct with exported fields and JSON tags, copies the values from the private fields, and then marshals it to JSON.

Example:

email := common.NewFullEmailMessage("sender@example.com", []string{"recipient@example.com"}, "Subject", []string{"cc@example.com"}, []string{"bcc@example.com"}, "replyto@example.com", "This is the email content.", "<p>This is the email content.</p>", []common.Attachment{*common.NewAttachment("attachment1.txt", []byte("file content"))})

jsonData, err := json.Marshal(email)
if err != nil {
    fmt.Println("Error marshaling to JSON:", err)
    return
}
fmt.Println("JSON output:", string(jsonData))
Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {

	email := common.NewFullEmailMessage(
		"sender@example.com",
		[]string{"recipient@example.com"},
		"Subject",
		[]string{"cc@example.com"},
		[]string{"bcc@example.com"},
		"replyto@example.com",
		"This is the email content.",
		"<p>This is the email content.</p>",
		[]common.Attachment{
			*common.NewAttachment("attachment1.txt", []byte("file content")),
		},
	)
	jsonData, err := json.Marshal(email)
	if err != nil {
		fmt.Println("Error marshaling to JSON:", err)
		return
	}
	fmt.Println("JSON output:", string(jsonData))
}
Output:

JSON output: {"from":"sender@example.com","to":["recipient@example.com"],"cc":["cc@example.com"],"bcc":["bcc@example.com"],"replyTo":"replyto@example.com","subject":"Subject","text":"This is the email content.","html":"\u003cp\u003eThis is the email content.\u003c/p\u003e","attachments":[{"filename":"attachment1.txt","content":"ZmlsZSBjb250ZW50"}]}

func (*EmailMessage) SetAttachments

func (e *EmailMessage) SetAttachments(attachments []Attachment) *EmailMessage

SetAttachments sets the attachments for the email.

Parameters:

  • attachments: A slice of Attachment structs to be included in the email.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetBCC

func (e *EmailMessage) SetBCC(bcc []string) *EmailMessage

SetBCC sets the BCC recipients email addresses.

Parameters:

  • bcc: A slice of BCC recipient email addresses.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetCC

func (e *EmailMessage) SetCC(cc []string) *EmailMessage

SetCC sets the CC recipients email addresses.

Parameters:

  • cc: A slice of CC recipient email addresses.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetCustomHtmlSanitizer

func (e *EmailMessage) SetCustomHtmlSanitizer(s sanitizer.Sanitizer) *EmailMessage

SetCustomHtmlSanitizer sets a custom sanitizer for HTML content. WARNING: Using a custom HTML sanitizer may introduce security risks if the sanitizer does not properly handle potentially dangerous content. Ensure that the custom sanitizer is thoroughly tested and used with caution.

Parameters:

  • s: The custom Sanitizer implementation for HTML content.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetCustomTextSanitizer

func (e *EmailMessage) SetCustomTextSanitizer(s sanitizer.Sanitizer) *EmailMessage

SetCustomTextSanitizer sets a custom sanitizer for text content. WARNING: Using a custom text sanitizer may introduce security risks if the sanitizer does not properly handle potentially dangerous content. Ensure that the custom sanitizer is thoroughly tested and used with caution.

Parameters:

  • s: The custom Sanitizer implementation for text content.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetFrom

func (e *EmailMessage) SetFrom(from string) *EmailMessage

SetFrom sets the sender email address.

Parameters:

  • from: The sender email address.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetHTML

func (e *EmailMessage) SetHTML(html string) *EmailMessage

SetHTML sets the HTML content of the email.

Parameters:

  • html: The HTML content of the email.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetMaxAttachmentSize

func (e *EmailMessage) SetMaxAttachmentSize(size int) *EmailMessage

SetMaxAttachmentSize sets the maximum attachment size.

Parameters:

  • size: The maximum size for attachments in bytes. If set to a value less than 0, all attachments are allowed.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetReplyTo

func (e *EmailMessage) SetReplyTo(replyTo string) *EmailMessage

SetReplyTo sets the reply-to email address.

Parameters:

  • replyTo: The reply-to email address.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetSubject

func (e *EmailMessage) SetSubject(subject string) *EmailMessage

SetSubject sets the email subject.

Parameters:

  • subject: The email subject.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetText

func (e *EmailMessage) SetText(text string) *EmailMessage

SetText sets the plain text content of the email.

Parameters:

  • text: The plain text content of the email.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) SetTo

func (e *EmailMessage) SetTo(to []string) *EmailMessage

SetTo sets the recipient email addresses.

Parameters:

  • to: A slice of recipient email addresses.

Returns:

  • *EmailMessage: The EmailMessage struct pointer.

func (*EmailMessage) UnmarshalJSON

func (e *EmailMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler for EmailMessage This method converts a JSON representation into an EmailMessage struct. It creates an anonymous struct with exported fields and JSON tags, unmarshals the JSON data into this struct, and then copies the values to the private fields of the EmailMessage struct.

Example:

jsonData := `{
    "from": "sender@example.com",
    "to": ["recipient@example.com"],
    "cc": ["cc@example.com"],
    "bcc": ["bcc@example.com"],
    "replyTo": "replyto@example.com",
    "subject": "Subject",
    "text": "This is the email content.",
    "html": "<p>This is the email content.</p>",
    "attachments": [{"filename": "attachment1.txt", "content": "ZmlsZSBjb250ZW50"}] // base64 encoded "file content"
}`
var email common.EmailMessage
err := json.Unmarshal([]byte(jsonData), &email)
if err != nil {
    fmt.Println("Error unmarshaling from JSON:", err)
    return
}
fmt.Printf("Unmarshaled EmailMessage: %+v\n", email)
Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/darkrockmountain/gomail/common"
)

func main() {

	jsonInput := `{
	    "from": "sender@example.com",
	    "to": ["recipient@example.com"],
	    "cc": ["cc@example.com"],
	    "bcc": ["bcc@example.com"],
	    "replyTo": "replyto@example.com",
	    "subject": "Subject",
	    "text": "This is the email content.",
	    "html": "<p>This is the email content.</p>",
	    "attachments": [{"filename": "attachment1.txt", "content": "ZmlsZSBjb250ZW50"}]
	}`
	var email common.EmailMessage
	err := json.Unmarshal([]byte(jsonInput), &email)
	if err != nil {
		fmt.Println("Error unmarshaling from JSON:", err)
		return
	}

	jsonData, err := json.Marshal(&email)
	if err != nil {
		fmt.Println("Error marshaling to JSON:", err)
		return
	}
	fmt.Println("JSON output:", string(jsonData))
}
Output:

JSON output: {"from":"sender@example.com","to":["recipient@example.com"],"cc":["cc@example.com"],"bcc":["bcc@example.com"],"replyTo":"replyto@example.com","subject":"Subject","text":"This is the email content.","html":"\u003cp\u003eThis is the email content.\u003c/p\u003e","attachments":[{"filename":"attachment1.txt","content":"ZmlsZSBjb250ZW50"}]}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL