Skip to main content

lettre/
lib.rs

1//! Lettre is an email library that allows creating and sending messages. It provides:
2//!
3//! * An easy to use email builder
4//! * Pluggable email transports
5//! * Unicode support
6//! * Secure defaults
7//! * Async support
8//!
9//! Lettre requires Rust 1.74 or newer.
10//!
11//! ## Features
12//!
13//! This section lists each lettre feature and briefly explains it.
14//! More info about each module can be found in the corresponding module page.
15//!
16//! Features with `📫` near them are enabled by default.
17//!
18//! ### Typed message builder
19//!
20//! _Strongly typed [`message`] builder_
21//!
22//! * **builder** 📫: Enable the [`Message`] builder
23//! * **hostname** 📫: Try to use the actual system hostname in the `Message-ID` header
24//!
25//! ### SMTP transport
26//!
27//! _Send emails using [`SMTP`]_
28//!
29//! * **smtp-transport** 📫: Enable the SMTP transport
30//! * **pool** 📫: Connection pool for SMTP transport
31//! * **hostname** 📫: Try to use the actual system hostname for the SMTP `CLIENTID`
32//!
33//! #### SMTP over TLS via the native-tls crate
34//!
35//! _Secure SMTP connections using TLS from the `native-tls` crate_
36//!
37//! Uses schannel on Windows, Security-Framework on macOS, and OpenSSL
38//! on all other platforms.
39//!
40//! * **native-tls** 📫: TLS support for the synchronous version of the API
41//! * **tokio1-native-tls**: TLS support for the `tokio1` async version of the API
42//!
43//! NOTE: native-tls isn't supported with `async-std`
44//!
45//! ##### Building lettre with OpenSSL
46//!
47//! When building lettre with native-tls on a system that makes
48//! use of OpenSSL, the following packages will need to be installed
49//! in order for the build and the compiled program to run properly.
50//!
51//! | Distro       | Build-time packages        | Runtime packages             |
52//! | ------------ | -------------------------- | ---------------------------- |
53//! | Debian       | `pkg-config`, `libssl-dev` | `libssl3`, `ca-certificates` |
54//! | Alpine Linux | `pkgconf`, `openssl-dev`   | `libssl3`, `ca-certificates` |
55//!
56//! #### SMTP over TLS via the boring crate (Boring TLS)
57//!
58//! _Secure SMTP connections using TLS from the `boring-tls` crate_
59//!
60//! * **boring-tls**: TLS support for the synchronous version of the API
61//! * **tokio1-boring-tls**: TLS support for the `tokio1` async version of the API
62//!
63//! NOTE: boring-tls isn't supported with `async-std`
64//!
65//! #### SMTP over TLS via the rustls crate
66//!
67//! _Secure SMTP connections using TLS from the `rustls` crate_
68//!
69//! * **rustls**: TLS support for the synchronous version of the API
70//! * **tokio1-rustls**: TLS support for the `tokio1` async version of the API
71//! * **async-std1-rustls**: TLS support for the `async-std1` async version of the API
72//!
73//! ##### rustls crypto backends
74//!
75//! _The crypto implementation to use with rustls_
76//!
77//! When the `rustls` feature is enabled, one of the following crypto backends MUST also
78//! be enabled.
79//!
80//! * **aws-lc-rs**: use [AWS-LC] (via [`aws-lc-rs`]) as the `rustls` crypto backend
81//! * **ring**: use [`ring`] as the `rustls` crypto backend
82//! * **rustls-no-provider**: don't install a default crypto provider, allowing the use
83//!   of a custom one (see [Custom rustls crypto providers](#custom-rustls-crypto-providers) below)
84//!
85//! When enabling `aws-lc-rs`, the `fips` feature can also be enabled to have
86//! rustls use the FIPS certified module of AWS-LC.
87//!
88//! `aws-lc-rs` may require cmake on some platforms to compile.
89//! `fips` always requires cmake and the Go compiler to compile.
90//!
91//! ##### Custom rustls crypto providers
92//!
93//! _Bring your own [`rustls`] crypto provider_
94//!
95//! By enabling the `rustls-no-provider` feature instead of `aws-lc-rs` or `ring`,
96//! you can use any [`rustls`]-compatible crypto provider such as
97//! [`rustls-graviola`], [`rustls-rustcrypto`] or others.
98//!
99//! The provider must be installed before using lettre by calling
100//! [`CryptoProvider::install_default`]:
101//!
102//! ```rust
103//! # mod rustls_graviola {
104//! #     pub struct FakeProvider;
105//! #     impl FakeProvider {
106//! #         pub fn install_default(self) -> Result<(), String> { Ok(()) }
107//! #     }
108//! #     pub fn default_provider() -> FakeProvider { FakeProvider }
109//! # }
110//! // Example using the `rustls-graviola` crypto provider crate.
111//! // Refer to your provider's documentation for the correct setup.
112//! rustls_graviola::default_provider()
113//!     .install_default()
114//!     .expect("Failed to install crypto provider");
115//! ```
116//!
117//! If `aws-lc-rs` or `ring` is enabled alongside `rustls-no-provider`, the
118//! globally installed provider (if any) takes precedence. If none is installed,
119//! lettre falls back to the feature-selected provider.
120//!
121//! [`CryptoProvider::install_default`]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html#method.install_default
122//! [`rustls-graviola`]: https://crates.io/crates/rustls-graviola
123//! [`rustls-rustcrypto`]: https://crates.io/crates/rustls-rustcrypto
124//!
125//! ##### rustls certificate verification backend
126//!
127//! _The TLS certificate verification backend to use with rustls_
128//!
129//! When the `rustls` feature is enabled, one of the following verification backends
130//! MUST also be enabled.
131//!
132//! * **rustls-platform-verifier**: verify TLS certificate using the OS's native certificate store (see [`rustls-platform-verifier`])
133//! * **rustls-native-certs**: verify TLS certificates using the platform's native certificate store (see [`rustls-native-certs`]) - when in doubt use `rustls-platform-verifier`
134//! * **webpki-roots**: verify TLS certificates against Mozilla's root certificates (see [`webpki-roots`])
135//!
136//! The following packages will need to be installed in order for the build
137//! stage and the compiled program to run properly.
138//!
139//! | Verification backend       | Distro       | Build-time packages        | Runtime packages             |
140//! | ---------------------      | ------------ | -------------------------- | ---------------------------- |
141//! | `rustls-platform-verifier` | Debian       | none                       | `ca-certificates`            |
142//! | `rustls-platform-verifier` | Alpine Linux | none                       | `ca-certificates`            |
143//! | `rustls-native-certs`      | Debian       | none                       | `ca-certificates`            |
144//! | `rustls-native-certs`      | Alpine Linux | none                       | `ca-certificates`            |
145//! | `webpki-roots`             | any          | none                       | none                         |
146//!
147//! ### Sendmail transport
148//!
149//! _Send emails using the [`sendmail`] command_
150//!
151//! * **sendmail-transport**: Enable the `sendmail` transport
152//!
153//! ### File transport
154//!
155//! _Save emails as an `.eml` [`file`]_
156//!
157//! * **file-transport**: Enable the file transport (saves emails into an `.eml` file)
158//! * **file-transport-envelope**: Allow writing the envelope into a JSON file (additionally saves envelopes into a `.json` file)
159//!
160//! ### Async execution runtimes
161//!
162//! _Use [tokio] or [async-std] as an async execution runtime for sending emails_
163//!
164//! The correct runtime version must be chosen in order for lettre to work correctly.
165//! For example, when sending emails from a Tokio 1.x context, the Tokio 1.x executor
166//! ([`Tokio1Executor`]) must be used. Using a different version (for example Tokio 0.2.x),
167//! or async-std, would result in a runtime panic.
168//!
169//! * **tokio1**: Allow to asynchronously send emails using [Tokio 1.x]
170//! * **async-std1**: Allow to asynchronously send emails using [async-std 1.x]
171//!
172//! NOTE: native-tls isn't supported with `async-std`
173//!
174//! ### Misc features
175//!
176//! _Additional features_
177//!
178//! * **serde**: Serialization/Deserialization of entities
179//! * **tracing**: Logging using the `tracing` crate
180//! * **mime03**: Allow creating a [`ContentType`] from an existing [mime 0.3] `Mime` struct
181//! * **dkim**: Add support for signing email with DKIM
182//! * **web**: WebAssembly support using the `web-time` crate for time operations
183//!
184//! [`SMTP`]: crate::transport::smtp
185//! [`sendmail`]: crate::transport::sendmail
186//! [`file`]: crate::transport::file
187//! [`ContentType`]: crate::message::header::ContentType
188//! [tokio]: https://docs.rs/tokio/1
189//! [async-std]: https://docs.rs/async-std/1
190//! [AWS-LC]: https://github.com/aws/aws-lc
191//! [`aws-lc-rs`]: https://crates.io/crates/aws-lc-rs
192//! [`ring`]: https://crates.io/crates/ring
193//! [`rustls-platform-verifier`]: https://crates.io/crates/rustls-platform-verifier
194//! [`rustls-native-certs`]: https://crates.io/crates/rustls-native-certs
195//! [`webpki-roots`]: https://crates.io/crates/webpki-roots
196//! [Tokio 1.x]: https://docs.rs/tokio/1
197//! [async-std 1.x]: https://docs.rs/async-std/1
198//! [mime 0.3]: https://docs.rs/mime/0.3
199//! [DKIM]: https://datatracker.ietf.org/doc/html/rfc6376
200
201#![doc(html_root_url = "https://docs.rs/crate/lettre/0.11.23")]
202#![doc(html_favicon_url = "https://lettre.rs/favicon.ico")]
203#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/15113230?v=4")]
204#![forbid(unsafe_code)]
205#![deny(
206    unreachable_pub,
207    missing_copy_implementations,
208    trivial_casts,
209    trivial_numeric_casts,
210    unstable_features,
211    unused_import_braces,
212    rust_2018_idioms,
213    clippy::string_add,
214    clippy::string_add_assign,
215    clippy::clone_on_ref_ptr,
216    clippy::verbose_file_reads,
217    clippy::unnecessary_self_imports,
218    clippy::implicit_clone,
219    clippy::mem_forget,
220    clippy::cast_lossless,
221    clippy::inefficient_to_string,
222    clippy::inline_always,
223    clippy::linkedlist,
224    clippy::macro_use_imports,
225    clippy::manual_assert,
226    clippy::unnecessary_join,
227    clippy::wildcard_imports,
228    clippy::str_to_string,
229    clippy::empty_structs_with_brackets,
230    clippy::zero_sized_map_values,
231    clippy::manual_let_else,
232    clippy::semicolon_if_nothing_returned,
233    clippy::unnecessary_wraps,
234    clippy::doc_markdown,
235    clippy::explicit_iter_loop,
236    clippy::redundant_closure_for_method_calls,
237    // Rust 1.86: clippy::unnecessary_semicolon,
238)]
239#![cfg_attr(docsrs, feature(doc_cfg))]
240
241#[cfg(not(lettre_ignore_tls_mismatch))]
242mod compiletime_checks {
243    #[cfg(all(
244        feature = "rustls",
245        not(feature = "aws-lc-rs"),
246        not(feature = "ring"),
247        not(feature = "rustls-no-provider")
248    ))]
249    compile_error!(
250        "feature `rustls` also requires either the `aws-lc-rs`, the `ring` or the `rustls-no-provider` feature to be enabled.
251    When using `rustls-no-provider` a custom `rustls` crypto provider must be installed at runtime by calling `install_default()` on the provider before using lettre, or it will panic."
252    );
253
254    #[cfg(all(
255        feature = "rustls",
256        not(feature = "rustls-platform-verifier"),
257        not(feature = "rustls-native-certs"),
258        not(feature = "webpki-roots")
259    ))]
260    compile_error!(
261        "feature `rustls` also requires either the `rustls-platform-verifier`, the `rustls-native-certs`
262    or the `webpki-roots` feature to be enabled"
263    );
264
265    #[cfg(all(feature = "native-tls", feature = "boring-tls"))]
266    compile_error!("feature \"native-tls\" and feature \"boring-tls\" cannot be enabled at the same time, otherwise
267    the executable will fail to link.");
268
269    #[cfg(all(
270        feature = "tokio1",
271        feature = "native-tls",
272        not(feature = "tokio1-native-tls")
273    ))]
274    compile_error!("Lettre is being built with the `tokio1` and the `native-tls` features, but the `tokio1-native-tls` feature hasn't been turned on.
275    If you were trying to opt into `rustls` and did not activate `native-tls`, disable the default-features of lettre in `Cargo.toml` and manually add the required features.
276    Make sure to apply the same to any of your crate dependencies that use the `lettre` crate.");
277
278    #[cfg(all(feature = "tokio1", feature = "rustls", not(feature = "tokio1-rustls")))]
279    compile_error!("Lettre is being built with the `tokio1` and the `rustls` features, but the `tokio1-rustls` feature hasn't been turned on.
280    If you'd like to use `native-tls` make sure that the `rustls` feature hasn't been enabled by mistake.
281    Make sure to apply the same to any of your crate dependencies that use the `lettre` crate.");
282
283    #[cfg(all(
284        feature = "tokio1",
285        feature = "boring-tls",
286        not(feature = "tokio1-boring-tls")
287    ))]
288    compile_error!("Lettre is being built with the `tokio1` and the `boring-tls` features, but the `tokio1-boring-tls` feature hasn't been turned on.
289    If you'd like to use `boring-tls` make sure that the `rustls` feature hasn't been enabled by mistake.
290    Make sure to apply the same to any of your crate dependencies that use the `lettre` crate.");
291
292    #[cfg(all(feature = "async-std1", feature = "native-tls"))]
293    compile_error!("Lettre is being built with the `async-std1` and the `native-tls` features, but the async-std integration doesn't support native-tls yet.
294If you'd like to work on the issue please take a look at https://github.com/lettre/lettre/issues/576.
295If you were trying to opt into `rustls` and did not activate `native-tls`, disable the default-features of lettre in `Cargo.toml` and manually add the required features.
296Make sure to apply the same to any of your crate dependencies that use the `lettre` crate.");
297
298    #[cfg(all(
299        feature = "async-std1",
300        feature = "rustls",
301        not(feature = "async-std1-rustls")
302    ))]
303    compile_error!("Lettre is being built with the `async-std1` and the `rustls` features, but the `async-std1-rustls` feature hasn't been turned on.
304If you'd like to use `native-tls` make sure that the `rustls` hasn't been enabled by mistake.
305Make sure to apply the same to any of your crate dependencies that use the `lettre` crate.");
306}
307
308pub mod address;
309#[cfg(any(feature = "smtp-transport", feature = "dkim"))]
310mod base64;
311pub mod error;
312#[cfg(any(feature = "tokio1", feature = "async-std1"))]
313mod executor;
314#[cfg(feature = "builder")]
315#[cfg_attr(docsrs, doc(cfg(feature = "builder")))]
316pub mod message;
317#[cfg(feature = "rustls")]
318mod rustls_crypto;
319mod time;
320pub mod transport;
321
322use std::error::Error as StdError;
323
324#[cfg(feature = "async-std1")]
325pub use self::executor::AsyncStd1Executor;
326#[cfg(any(feature = "tokio1", feature = "async-std1"))]
327pub use self::executor::Executor;
328#[cfg(feature = "tokio1")]
329pub use self::executor::Tokio1Executor;
330#[cfg(any(feature = "tokio1", feature = "async-std1"))]
331#[doc(inline)]
332pub use self::transport::AsyncTransport;
333pub use crate::address::Address;
334#[cfg(feature = "builder")]
335#[doc(inline)]
336pub use crate::message::Message;
337#[doc(inline)]
338pub use crate::transport::Transport;
339#[cfg(all(
340    feature = "file-transport",
341    any(feature = "tokio1", feature = "async-std1")
342))]
343#[doc(inline)]
344pub use crate::transport::file::AsyncFileTransport;
345#[cfg(feature = "file-transport")]
346#[doc(inline)]
347pub use crate::transport::file::FileTransport;
348#[cfg(all(
349    feature = "sendmail-transport",
350    any(feature = "tokio1", feature = "async-std1")
351))]
352#[doc(inline)]
353pub use crate::transport::sendmail::AsyncSendmailTransport;
354#[cfg(feature = "sendmail-transport")]
355#[doc(inline)]
356pub use crate::transport::sendmail::SendmailTransport;
357#[cfg(all(
358    feature = "smtp-transport",
359    any(feature = "tokio1", feature = "async-std1")
360))]
361pub use crate::transport::smtp::AsyncSmtpTransport;
362#[cfg(feature = "smtp-transport")]
363pub use crate::transport::smtp::SmtpTransport;
364use crate::{address::Envelope, error::Error};
365
366pub(crate) type BoxError = Box<dyn StdError + Send + Sync>;
367
368#[cfg(test)]
369#[cfg(feature = "builder")]
370mod test {
371    use super::*;
372    use crate::message::{Mailbox, Mailboxes, header, header::Headers};
373
374    #[test]
375    fn envelope_from_headers() {
376        let from = Mailboxes::new().with("kayo@example.com".parse().unwrap());
377        let to = Mailboxes::new().with("amousset@example.com".parse().unwrap());
378
379        let mut headers = Headers::new();
380        headers.set(header::From(from));
381        headers.set(header::To(to));
382
383        assert_eq!(
384            Envelope::try_from(&headers).unwrap(),
385            Envelope::new(
386                Some(Address::new("kayo", "example.com").unwrap()),
387                vec![Address::new("amousset", "example.com").unwrap()]
388            )
389            .unwrap()
390        );
391    }
392
393    #[test]
394    fn envelope_from_headers_sender() {
395        let from = Mailboxes::new().with("kayo@example.com".parse().unwrap());
396        let sender = Mailbox::new(None, "kayo2@example.com".parse().unwrap());
397        let to = Mailboxes::new().with("amousset@example.com".parse().unwrap());
398
399        let mut headers = Headers::new();
400        headers.set(header::From::from(from));
401        headers.set(header::Sender::from(sender));
402        headers.set(header::To::from(to));
403
404        assert_eq!(
405            Envelope::try_from(&headers).unwrap(),
406            Envelope::new(
407                Some(Address::new("kayo2", "example.com").unwrap()),
408                vec![Address::new("amousset", "example.com").unwrap()]
409            )
410            .unwrap()
411        );
412    }
413
414    #[test]
415    fn envelope_from_headers_no_to() {
416        let from = Mailboxes::new().with("kayo@example.com".parse().unwrap());
417        let sender = Mailbox::new(None, "kayo2@example.com".parse().unwrap());
418
419        let mut headers = Headers::new();
420        headers.set(header::From::from(from));
421        headers.set(header::Sender::from(sender));
422
423        assert!(Envelope::try_from(&headers).is_err(),);
424    }
425}