send_email/
lib.rs

1//! Simple rust email sender.
2//! This library is mostly a wrapper for lettre crate.
3//! See examples and documentations on https://github.com/harryhanYuhao/rust_send_email
4#![warn(missing_docs)]
5use lettre::message::header::ContentType;
6use lettre::message::{Mailbox, MultiPart};
7use lettre::{Message, SmtpTransport, Transport};
8
9mod sender;
10mod recipient;
11mod email;
12
13pub use sender::SmtpServer;
14pub use sender::Sender;
15pub use recipient::{Recipient, Category};
16pub use email::EmailContent;
17
18/// Send email, providing the sender, email content, and recipients.
19pub fn send_email(
20    sender: &Sender,
21    content: &EmailContent,
22    recipient: &[Recipient],
23) -> Result<(), Box<dyn std::error::Error>> {
24    // Create Sender info
25    let creds = sender.get_credentials();
26    let send_mailbox = Mailbox::new(sender.get_name(), sender.get_address());
27    let reply_addr = sender.get_reply_address();
28    let smtp_server = sender.get_smtp_server();
29
30    // Content type
31    let content_type = match content.is_html {
32        true => ContentType::TEXT_HTML,
33        false => ContentType::TEXT_PLAIN,
34    };
35
36    // add body and attachments
37    let mut multipart = MultiPart::mixed().singlepart(
38        lettre::message::SinglePart::builder()
39            .header(content_type)
40            .body(String::from(content.content.to_owned())),
41    );
42    for i in content.attachments.iter() {
43        multipart = multipart.singlepart(i.clone());
44    }
45
46    // configure to send to multiple recipients
47    let mut email = Message::builder();
48    for i in recipient {
49        match i.category {
50            Category::To => email = email.to(Mailbox::new(i.get_name(), i.get_address())),
51            Category::Cc => email = email.cc(Mailbox::new(i.get_name(), i.get_address())),
52            Category::Bcc => email = email.bcc(Mailbox::new(i.get_name(), i.get_address())),
53        }
54    }
55
56    let email = email
57        .from(send_mailbox)
58        .reply_to(reply_addr.into())
59        .subject(content.subject.to_owned())
60        .multipart(multipart)
61        .unwrap();
62
63    // Open a secure connection to the SMTP server using STARTTLS
64    let mailer = SmtpTransport::starttls_relay(smtp_server)
65        .unwrap() // Unwrap the Result, panics in case of error
66        .credentials(creds) // Provide the credentials to the transport
67        .build(); // Construct the transport
68
69    // Attempt to send the email via the SMTP transport
70    mailer.send(&email)?;
71    Ok(())
72}