EmailAddress

Struct EmailAddress 

Source
pub struct EmailAddress {
    pub local: String,
    pub domain: String,
    pub display_name: Option<String>,
}
Expand description

Email address structure

Fields§

§local: String

Parte local (antes do @)

§domain: String

Domínio (depois do @)

§display_name: Option<String>

Nome de exibição opcional

Implementations§

Source§

impl EmailAddress

Source

pub fn new(email: impl AsRef<str>) -> Result<Self>

Creates new email address

Examples found in repository?
examples/basic_usage.rs (line 7)
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 23)
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_string(&self) -> String

Converts to complete string

Source

pub fn is_valid(&self) -> bool

Validates email format

Examples found in repository?
examples/basic_usage.rs (line 43)
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 with_name(self, name: impl Into<String>) -> Self

Sets display name

Source

pub fn to_rfc5322(&self) -> String

Formats for RFC 5322 (with display name if present)

Trait Implementations§

Source§

impl Clone for EmailAddress

Source§

fn clone(&self) -> EmailAddress

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 EmailAddress

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Display for EmailAddress

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Hash for EmailAddress

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for EmailAddress

Source§

fn eq(&self, other: &EmailAddress) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for EmailAddress

Source§

impl StructuralPartialEq for EmailAddress

Auto Trait Implementations§

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.