Email

Struct Email 

Source
pub struct Email {
    pub id: String,
    pub from: EmailAddress,
    pub to: Vec<EmailAddress>,
    pub cc: Vec<EmailAddress>,
    pub bcc: Vec<EmailAddress>,
    pub subject: String,
    pub body: String,
    pub html_body: Option<String>,
    pub headers: HashMap<String, String>,
    pub date: DateTime,
    pub attachments: Vec<Attachment>,
}
Expand description

Complete email message

Fields§

§id: String

Unique message ID

§from: EmailAddress

Sender

§to: Vec<EmailAddress>

Recipients

§cc: Vec<EmailAddress>

Carbon copy

§bcc: Vec<EmailAddress>

Blind carbon copy

§subject: String

Subject

§body: String

Message body (plain text)

§html_body: Option<String>

HTML body (optional)

§headers: HashMap<String, String>

Custom headers

§date: DateTime

Send date

§attachments: Vec<Attachment>

Attachments

Implementations§

Source§

impl Email

Source

pub fn new( from: EmailAddress, to: Vec<EmailAddress>, subject: String, body: String, ) -> Self

Creates new message

Examples found in repository?
examples/basic_usage.rs (lines 15-20)
3fn main() {
4    println!("=== Avila Cell - Email Protocol Demo ===\n");
5
6    // Criar endereços de email
7    let from = EmailAddress::new("sender@avila.inc").unwrap();
8    let to = vec![EmailAddress::new("recipient@avila.inc").unwrap()];
9
10    println!("✓ Endereços criados:");
11    println!("  De: {}", from);
12    println!("  Para: {}", to[0]);
13
14    // Criar email
15    let mut email = Email::new(
16        from.clone(),
17        to,
18        "Teste Avila Cell".to_string(),
19        "Esta é uma mensagem de teste do ecossistema Avila!".to_string(),
20    );
21
22    // Adicionar CC
23    email.add_cc(EmailAddress::new("cc@avila.inc").unwrap());
24
25    // Adicionar header customizado
26    email.add_header("X-Avila-Version".to_string(), "0.1.0".to_string());
27
28    println!("\n✓ Email criado:");
29    println!("  Message-ID: {}", email.id);
30    println!("  Assunto: {}", email.subject);
31    println!("  CC: {:?}", email.cc);
32
33    // Converter para RFC 5322
34    let rfc5322 = email.to_rfc5322();
35
36    println!("\n✓ Formato RFC 5322:");
37    println!("{}", "=".repeat(60));
38    println!("{}", rfc5322);
39    println!("{}", "=".repeat(60));
40
41    // Validar endereços
42    println!("\n✓ Validações:");
43    println!("  {} é válido? {}", from, from.is_valid());
44
45    let invalid = EmailAddress::new("test@localhost").unwrap();
46    println!("  {} é válido? {}", invalid, invalid.is_valid());
47
48    println!("\n✅ Demo concluído com sucesso!");
49}
More examples
Hide additional examples
examples/gmail_client.rs (lines 29-46)
4fn main() {
5    println!("=== Avila Cell - Gmail SMTP Client Demo ===\n");
6
7    // Configuração do Gmail
8    let _smtp_server = NetworkAddress::new("smtp.gmail.com", 587); // TLS/STARTTLS
9    // let smtp_server = NetworkAddress::new("smtp.gmail.com", 465); // SSL
10
11    println!("📧 Conectando ao Gmail SMTP...");
12    println!("   Servidor: smtp.gmail.com:587");
13    println!("   Protocolo: SMTP com STARTTLS\n");
14
15    // NOTA: Para usar Gmail você precisa:
16    // 1. Ativar "App Passwords" na sua conta Google
17    // 2. Ou usar OAuth2 (não implementado ainda)
18
19    let username = "seu-email@gmail.com";
20    let _app_password = "sua-senha-de-app"; // 16 caracteres sem espaços
21
22    // Criar email
23    match EmailAddress::new(username) {
24        Ok(from) => {
25            match EmailAddress::new("destinatario@example.com") {
26                Ok(to_addr) => {
27                    let to = vec![to_addr];
28
29    let mut email = Email::new(
30        from.clone(),
31        to,
32        "Teste do Avila Cell via Gmail".to_string(),
33        r#"Olá!
34
35Este é um email enviado usando o Avila Cell,
36uma biblioteca Rust nativa para protocolos de email.
37
38Características:
39- 100% Rust nativo
40- Sem dependências externas pesadas
41- Suporte a SMTP, POP3 e IMAP
42- Compatível com Gmail, Outlook, etc.
43
44Enviado por: Avila Cell v0.1.0
45"#.to_string(),
46    );
47
48    // Headers adicionais
49    email.add_header("X-Mailer".to_string(), "Avila Cell 0.1.0".to_string());
50    email.add_header("X-Priority".to_string(), "3".to_string()); // Normal priority
51
52    println!("✉️  Email preparado:");
53    println!("   De: {}", email.from);
54    println!("   Para: {:?}", email.to);
55    println!("   Assunto: {}", email.subject);
56    println!("   Message-ID: {}\n", email.id);
57
58    // DIFERENÇAS DO BASIC USAGE:
59    println!("🔍 Diferenças do exemplo básico:");
60    println!("   ❌ Básico: Apenas cria estruturas de dados");
61    println!("   ✅ Gmail: Conexão real com servidor SMTP");
62    println!("   ❌ Básico: Não envia nada");
63    println!("   ✅ Gmail: Envia email de verdade");
64    println!("   ❌ Básico: Sem autenticação");
65    println!("   ✅ Gmail: Autenticação com credenciais");
66    println!("   ❌ Básico: Sem criptografia");
67    println!("   ✅ Gmail: TLS/SSL obrigatório\n");
68
69    // Conectar (comentado pois precisa de credenciais reais)
70    println!("⚠️  AVISO: Conexão desabilitada neste demo");
71    println!("   Para enviar emails reais:");
72    println!("   1. Configure suas credenciais do Gmail");
73    println!("   2. Ative 'App Passwords' no Google");
74    println!("   3. Descomente o código de envio abaixo\n");
75
76    /*
77    // Descomentar para enviar de verdade:
78    match SmtpClient::connect(smtp_server).await {
79        Ok(mut client) => {
80            println!("✅ Conectado ao Gmail!");
81
82            // HELO/EHLO
83            client.helo("avila.inc").await?;
84            println!("✅ HELO enviado");
85
86            // Autenticação (necessário implementar STARTTLS + AUTH)
87            // client.auth_plain(username, app_password).await?;
88
89            // Enviar email
90            client.send_email(&email).await?;
91            println!("✅ Email enviado com sucesso!");
92
93            client.quit().await?;
94        }
95        Err(e) => {
96            eprintln!("❌ Erro ao conectar: {}", e);
97        }
98    }
99    */
100
101    println!("📊 Comparação detalhada:");
102    println!("\n┌─────────────────────┬──────────────┬─────────────┐");
103    println!("│ Recurso             │ Basic Usage  │ Gmail Client│");
104    println!("├─────────────────────┼──────────────┼─────────────┤");
105    println!("│ Criar estruturas    │      ✅      │      ✅     │");
106    println!("│ Validar emails      │      ✅      │      ✅     │");
107    println!("│ RFC 5322 format     │      ✅      │      ✅     │");
108    println!("│ Conexão TCP         │      ❌      │      ✅     │");
109    println!("│ TLS/SSL             │      ❌      │      ✅     │");
110    println!("│ Autenticação SMTP   │      ❌      │      ✅     │");
111    println!("│ Envio real          │      ❌      │      ✅     │");
112    println!("│ STARTTLS            │      ❌      │      ✅     │");
113    println!("└─────────────────────┴──────────────┴─────────────┘");
114
115    println!("\n✅ Demo concluído!");
116    println!("\n💡 Próximos passos:");
117    println!("   - Implementar STARTTLS");
118    println!("   - Implementar AUTH PLAIN/LOGIN");
119    println!("   - Implementar OAuth2 para Gmail");
120    println!("   - Adicionar suporte a anexos");
121    println!("   - Implementar HTML multipart");
122                }
123                Err(e) => eprintln!("Erro ao criar endereço de destino: {}", e),
124            }
125        }
126        Err(e) => eprintln!("Erro ao criar endereço de origem: {}", e),
127    }
128}
Source

pub fn add_cc(&mut self, address: EmailAddress)

Adds CC recipient

Examples found in repository?
examples/basic_usage.rs (line 23)
3fn main() {
4    println!("=== Avila Cell - Email Protocol Demo ===\n");
5
6    // Criar endereços de email
7    let from = EmailAddress::new("sender@avila.inc").unwrap();
8    let to = vec![EmailAddress::new("recipient@avila.inc").unwrap()];
9
10    println!("✓ Endereços criados:");
11    println!("  De: {}", from);
12    println!("  Para: {}", to[0]);
13
14    // Criar email
15    let mut email = Email::new(
16        from.clone(),
17        to,
18        "Teste Avila Cell".to_string(),
19        "Esta é uma mensagem de teste do ecossistema Avila!".to_string(),
20    );
21
22    // Adicionar CC
23    email.add_cc(EmailAddress::new("cc@avila.inc").unwrap());
24
25    // Adicionar header customizado
26    email.add_header("X-Avila-Version".to_string(), "0.1.0".to_string());
27
28    println!("\n✓ Email criado:");
29    println!("  Message-ID: {}", email.id);
30    println!("  Assunto: {}", email.subject);
31    println!("  CC: {:?}", email.cc);
32
33    // Converter para RFC 5322
34    let rfc5322 = email.to_rfc5322();
35
36    println!("\n✓ Formato RFC 5322:");
37    println!("{}", "=".repeat(60));
38    println!("{}", rfc5322);
39    println!("{}", "=".repeat(60));
40
41    // Validar endereços
42    println!("\n✓ Validações:");
43    println!("  {} é válido? {}", from, from.is_valid());
44
45    let invalid = EmailAddress::new("test@localhost").unwrap();
46    println!("  {} é válido? {}", invalid, invalid.is_valid());
47
48    println!("\n✅ Demo concluído com sucesso!");
49}
Source

pub fn add_bcc(&mut self, address: EmailAddress)

Adds BCC recipient

Source

pub fn add_attachment(&mut self, attachment: Attachment)

Adds attachment

Source

pub fn set_html_body(&mut self, html: String)

Sets HTML body

Source

pub fn add_header(&mut self, key: String, value: String)

Adds custom header

Examples found in repository?
examples/basic_usage.rs (line 26)
3fn main() {
4    println!("=== Avila Cell - Email Protocol Demo ===\n");
5
6    // Criar endereços de email
7    let from = EmailAddress::new("sender@avila.inc").unwrap();
8    let to = vec![EmailAddress::new("recipient@avila.inc").unwrap()];
9
10    println!("✓ Endereços criados:");
11    println!("  De: {}", from);
12    println!("  Para: {}", to[0]);
13
14    // Criar email
15    let mut email = Email::new(
16        from.clone(),
17        to,
18        "Teste Avila Cell".to_string(),
19        "Esta é uma mensagem de teste do ecossistema Avila!".to_string(),
20    );
21
22    // Adicionar CC
23    email.add_cc(EmailAddress::new("cc@avila.inc").unwrap());
24
25    // Adicionar header customizado
26    email.add_header("X-Avila-Version".to_string(), "0.1.0".to_string());
27
28    println!("\n✓ Email criado:");
29    println!("  Message-ID: {}", email.id);
30    println!("  Assunto: {}", email.subject);
31    println!("  CC: {:?}", email.cc);
32
33    // Converter para RFC 5322
34    let rfc5322 = email.to_rfc5322();
35
36    println!("\n✓ Formato RFC 5322:");
37    println!("{}", "=".repeat(60));
38    println!("{}", rfc5322);
39    println!("{}", "=".repeat(60));
40
41    // Validar endereços
42    println!("\n✓ Validações:");
43    println!("  {} é válido? {}", from, from.is_valid());
44
45    let invalid = EmailAddress::new("test@localhost").unwrap();
46    println!("  {} é válido? {}", invalid, invalid.is_valid());
47
48    println!("\n✅ Demo concluído com sucesso!");
49}
More examples
Hide additional examples
examples/gmail_client.rs (line 49)
4fn main() {
5    println!("=== Avila Cell - Gmail SMTP Client Demo ===\n");
6
7    // Configuração do Gmail
8    let _smtp_server = NetworkAddress::new("smtp.gmail.com", 587); // TLS/STARTTLS
9    // let smtp_server = NetworkAddress::new("smtp.gmail.com", 465); // SSL
10
11    println!("📧 Conectando ao Gmail SMTP...");
12    println!("   Servidor: smtp.gmail.com:587");
13    println!("   Protocolo: SMTP com STARTTLS\n");
14
15    // NOTA: Para usar Gmail você precisa:
16    // 1. Ativar "App Passwords" na sua conta Google
17    // 2. Ou usar OAuth2 (não implementado ainda)
18
19    let username = "seu-email@gmail.com";
20    let _app_password = "sua-senha-de-app"; // 16 caracteres sem espaços
21
22    // Criar email
23    match EmailAddress::new(username) {
24        Ok(from) => {
25            match EmailAddress::new("destinatario@example.com") {
26                Ok(to_addr) => {
27                    let to = vec![to_addr];
28
29    let mut email = Email::new(
30        from.clone(),
31        to,
32        "Teste do Avila Cell via Gmail".to_string(),
33        r#"Olá!
34
35Este é um email enviado usando o Avila Cell,
36uma biblioteca Rust nativa para protocolos de email.
37
38Características:
39- 100% Rust nativo
40- Sem dependências externas pesadas
41- Suporte a SMTP, POP3 e IMAP
42- Compatível com Gmail, Outlook, etc.
43
44Enviado por: Avila Cell v0.1.0
45"#.to_string(),
46    );
47
48    // Headers adicionais
49    email.add_header("X-Mailer".to_string(), "Avila Cell 0.1.0".to_string());
50    email.add_header("X-Priority".to_string(), "3".to_string()); // Normal priority
51
52    println!("✉️  Email preparado:");
53    println!("   De: {}", email.from);
54    println!("   Para: {:?}", email.to);
55    println!("   Assunto: {}", email.subject);
56    println!("   Message-ID: {}\n", email.id);
57
58    // DIFERENÇAS DO BASIC USAGE:
59    println!("🔍 Diferenças do exemplo básico:");
60    println!("   ❌ Básico: Apenas cria estruturas de dados");
61    println!("   ✅ Gmail: Conexão real com servidor SMTP");
62    println!("   ❌ Básico: Não envia nada");
63    println!("   ✅ Gmail: Envia email de verdade");
64    println!("   ❌ Básico: Sem autenticação");
65    println!("   ✅ Gmail: Autenticação com credenciais");
66    println!("   ❌ Básico: Sem criptografia");
67    println!("   ✅ Gmail: TLS/SSL obrigatório\n");
68
69    // Conectar (comentado pois precisa de credenciais reais)
70    println!("⚠️  AVISO: Conexão desabilitada neste demo");
71    println!("   Para enviar emails reais:");
72    println!("   1. Configure suas credenciais do Gmail");
73    println!("   2. Ative 'App Passwords' no Google");
74    println!("   3. Descomente o código de envio abaixo\n");
75
76    /*
77    // Descomentar para enviar de verdade:
78    match SmtpClient::connect(smtp_server).await {
79        Ok(mut client) => {
80            println!("✅ Conectado ao Gmail!");
81
82            // HELO/EHLO
83            client.helo("avila.inc").await?;
84            println!("✅ HELO enviado");
85
86            // Autenticação (necessário implementar STARTTLS + AUTH)
87            // client.auth_plain(username, app_password).await?;
88
89            // Enviar email
90            client.send_email(&email).await?;
91            println!("✅ Email enviado com sucesso!");
92
93            client.quit().await?;
94        }
95        Err(e) => {
96            eprintln!("❌ Erro ao conectar: {}", e);
97        }
98    }
99    */
100
101    println!("📊 Comparação detalhada:");
102    println!("\n┌─────────────────────┬──────────────┬─────────────┐");
103    println!("│ Recurso             │ Basic Usage  │ Gmail Client│");
104    println!("├─────────────────────┼──────────────┼─────────────┤");
105    println!("│ Criar estruturas    │      ✅      │      ✅     │");
106    println!("│ Validar emails      │      ✅      │      ✅     │");
107    println!("│ RFC 5322 format     │      ✅      │      ✅     │");
108    println!("│ Conexão TCP         │      ❌      │      ✅     │");
109    println!("│ TLS/SSL             │      ❌      │      ✅     │");
110    println!("│ Autenticação SMTP   │      ❌      │      ✅     │");
111    println!("│ Envio real          │      ❌      │      ✅     │");
112    println!("│ STARTTLS            │      ❌      │      ✅     │");
113    println!("└─────────────────────┴──────────────┴─────────────┘");
114
115    println!("\n✅ Demo concluído!");
116    println!("\n💡 Próximos passos:");
117    println!("   - Implementar STARTTLS");
118    println!("   - Implementar AUTH PLAIN/LOGIN");
119    println!("   - Implementar OAuth2 para Gmail");
120    println!("   - Adicionar suporte a anexos");
121    println!("   - Implementar HTML multipart");
122                }
123                Err(e) => eprintln!("Erro ao criar endereço de destino: {}", e),
124            }
125        }
126        Err(e) => eprintln!("Erro ao criar endereço de origem: {}", e),
127    }
128}
Source

pub fn to_rfc5322(&self) -> String

Converts to RFC 5322 format (email wire format)

Examples found in repository?
examples/basic_usage.rs (line 34)
3fn main() {
4    println!("=== Avila Cell - Email Protocol Demo ===\n");
5
6    // Criar endereços de email
7    let from = EmailAddress::new("sender@avila.inc").unwrap();
8    let to = vec![EmailAddress::new("recipient@avila.inc").unwrap()];
9
10    println!("✓ Endereços criados:");
11    println!("  De: {}", from);
12    println!("  Para: {}", to[0]);
13
14    // Criar email
15    let mut email = Email::new(
16        from.clone(),
17        to,
18        "Teste Avila Cell".to_string(),
19        "Esta é uma mensagem de teste do ecossistema Avila!".to_string(),
20    );
21
22    // Adicionar CC
23    email.add_cc(EmailAddress::new("cc@avila.inc").unwrap());
24
25    // Adicionar header customizado
26    email.add_header("X-Avila-Version".to_string(), "0.1.0".to_string());
27
28    println!("\n✓ Email criado:");
29    println!("  Message-ID: {}", email.id);
30    println!("  Assunto: {}", email.subject);
31    println!("  CC: {:?}", email.cc);
32
33    // Converter para RFC 5322
34    let rfc5322 = email.to_rfc5322();
35
36    println!("\n✓ Formato RFC 5322:");
37    println!("{}", "=".repeat(60));
38    println!("{}", rfc5322);
39    println!("{}", "=".repeat(60));
40
41    // Validar endereços
42    println!("\n✓ Validações:");
43    println!("  {} é válido? {}", from, from.is_valid());
44
45    let invalid = EmailAddress::new("test@localhost").unwrap();
46    println!("  {} é válido? {}", invalid, invalid.is_valid());
47
48    println!("\n✅ Demo concluído com sucesso!");
49}
Source

pub fn to_mime(&self) -> String

Converts to MIME multipart format

Trait Implementations§

Source§

impl Clone for Email

Source§

fn clone(&self) -> Email

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Email

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Email

§

impl RefUnwindSafe for Email

§

impl Send for Email

§

impl Sync for Email

§

impl Unpin for Email

§

impl UnwindSafe for Email

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.