pub struct EmailAddress {
pub local: String,
pub domain: String,
pub display_name: Option<String>,
}Expand description
Email address structure
Fields§
§local: StringParte local (antes do @)
domain: StringDomínio (depois do @)
display_name: Option<String>Nome de exibição opcional
Implementations§
Source§impl EmailAddress
impl EmailAddress
Sourcepub fn new(email: impl AsRef<str>) -> Result<Self>
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
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}Sourcepub fn is_valid(&self) -> bool
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}Sourcepub fn to_rfc5322(&self) -> String
pub fn to_rfc5322(&self) -> String
Formats for RFC 5322 (with display name if present)
Trait Implementations§
Source§impl Clone for EmailAddress
impl Clone for EmailAddress
Source§fn clone(&self) -> EmailAddress
fn clone(&self) -> EmailAddress
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for EmailAddress
impl Debug for EmailAddress
Source§impl Display for EmailAddress
impl Display for EmailAddress
Source§impl Hash for EmailAddress
impl Hash for EmailAddress
Source§impl PartialEq for EmailAddress
impl PartialEq for EmailAddress
impl Eq for EmailAddress
impl StructuralPartialEq for EmailAddress
Auto Trait Implementations§
impl Freeze for EmailAddress
impl RefUnwindSafe for EmailAddress
impl Send for EmailAddress
impl Sync for EmailAddress
impl Unpin for EmailAddress
impl UnwindSafe for EmailAddress
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more