pax_global_header00006660000000000000000000000064147454447520014532gustar00rootroot0000000000000052 comment=962518a299c5b6da5c44d9f4e090a10d14e8a236 mail-send-0.5.0/000077500000000000000000000000001474544475200134055ustar00rootroot00000000000000mail-send-0.5.0/.github/000077500000000000000000000000001474544475200147455ustar00rootroot00000000000000mail-send-0.5.0/.github/workflows/000077500000000000000000000000001474544475200170025ustar00rootroot00000000000000mail-send-0.5.0/.github/workflows/rust.yml000066400000000000000000000005071474544475200205240ustar00rootroot00000000000000name: "CI" on: push: branches: [ main ] pull_request: branches: [ main ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --all-features --verbose mail-send-0.5.0/.gitignore000066400000000000000000000005001474544475200153700ustar00rootroot00000000000000# Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk mail-send-0.5.0/CHANGELOG.md000066400000000000000000000041411474544475200152160ustar00rootroot00000000000000mail-send 0.5.0 ================================ - Bump `mail-parser` dependency to 0.10 - Bump `mail-builder` dependency to 0.4 - Bump `mail-auth` dependency to 0.6 mail-send 0.4.9 ================================ - Bump `rustls` dependency to 0.23 - Bump `tokio-rustls` dependency to 0.26 mail-send 0.4.8 ================================ - Bump `mail-auth` dependency to 0.4 - Bump `base64` dependency to 0.22 mail-send 0.4.7 ================================ - Added 'parser feature for `Message` conversion. mail-send 0.4.6 ================================ - Improved transparency procedure to also escape . - Removed `skip-ehlo` feature. mail-send 0.4.4 ================================ - Updated transparency procedure to escape . as well as . to prevent SMTP smuggling on vulnerable servers. mail-send 0.4.3 ================================ - Bump `rustls` dependency to 0.22 mail-send 0.4.2 ================================ - Bump `webpki-roots` dependency to 0.26 mail-send 0.4.1 ================================ - Bump `webpki-roots` dependency to 0.25 mail-send 0.4.0 ================================ - Bump `mail-builder` dependency to 0.3 mail-send 0.3.3 ================================ - Bump `rustls` dependency to 0.21 mail-send 0.3.2 ================================ - Fix: Extend buffer from bytes read while reading EHLO (#12). - Add an impl std::error::Error for mail_send::Error (#11) mail-send 0.3.1 ================================ - Fix: plain text connect issues (#10). mail-send 0.3.0 ================================ - Use of generics on TCP streams instead of static dispatch with enums. - Switch to `mail-auth` for DKIM authentication. mail-send 0.2.3 ================================ - Fix: Send gets stuck when the message has a binary attachment (#7) mail-send 0.2.2 ================================ - Bump up to mail-builder v0.2.2 mail-send 0.2.1 ================================ - Fixes to support mail-builder v0.2.1 mail-send 0.2.0 ================================ - Removed HTTP support. - API cleanup. mail-send 0.1.0 ================================ - Initial release. mail-send-0.5.0/Cargo.toml000066400000000000000000000032141474544475200153350ustar00rootroot00000000000000[package] name = "mail-send" description = "E-mail delivery library with SMTP and DKIM support" version = "0.5.0" edition = "2021" authors = [ "Stalwart Labs "] license = "Apache-2.0 OR MIT" repository = "https://github.com/stalwartlabs/mail-send" homepage = "https://github.com/stalwartlabs/mail-send" keywords = ["smtp", "dkim", "email", "mime", "mail"] categories = ["email"] readme = "README.md" [lib] doctest = false [dependencies] smtp-proto = { version = "0.1" } mail-auth = { version = "0.6", optional = true } mail-builder = { version = "0.4", optional = true } mail-parser = { version = "0.10", optional = true } base64 = "0.22" rand = { version = "0.8.5", optional = true } md5 = { version = "0.7.0", optional = true } tokio = { version = "1.23", features = ["net", "io-util", "time"]} rustls = { version = "0.23", default-features = false, features = ["std"]} tokio-rustls = { version = "0.26", default-features = false } webpki-roots = { version = "0.26"} rustls-pki-types = { version = "1" } gethostname = { version = "0.5"} [dev-dependencies] tokio = { version = "1.16", features = ["net", "io-util", "time", "rt-multi-thread", "macros"] } env_logger = "0.11.0" [features] default = ["digest-md5", "cram-md5", "builder", "dkim", "ring", "tls12"] builder = ["mail-builder"] parser = ["mail-parser"] dkim = ["mail-auth"] digest-md5 = ["md5", "rand"] cram-md5 = ["md5"] aws_lc_rs = ["rustls/aws_lc_rs", "tokio-rustls/aws_lc_rs"] aws-lc-rs = ["aws_lc_rs"] fips = ["rustls/fips", "tokio-rustls/fips"] logging = ["rustls/logging", "tokio-rustls/logging"] ring = ["rustls/ring", "tokio-rustls/ring"] tls12 = ["rustls/tls12", "tokio-rustls/tls12"] mail-send-0.5.0/LICENSE-APACHE000066400000000000000000000251371474544475200153410ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. mail-send-0.5.0/LICENSE-MIT000066400000000000000000000017771474544475200150550ustar00rootroot00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mail-send-0.5.0/README.md000066400000000000000000000076241474544475200146750ustar00rootroot00000000000000# mail-send [![crates.io](https://img.shields.io/crates/v/mail-send)](https://crates.io/crates/mail-send) [![build](https://github.com/stalwartlabs/mail-send/actions/workflows/rust.yml/badge.svg)](https://github.com/stalwartlabs/mail-send/actions/workflows/rust.yml) [![docs.rs](https://img.shields.io/docsrs/mail-send)](https://docs.rs/mail-send) [![crates.io](https://img.shields.io/crates/l/mail-send)](http://www.apache.org/licenses/LICENSE-2.0) _mail-send_ is a Rust library to build, sign and send e-mail messages via SMTP. It includes the following features: - Generates **e-mail** messages conforming to the Internet Message Format standard (_RFC 5322_). - Full **MIME** support (_RFC 2045 - 2049_) with automatic selection of the most optimal encoding for each message body part. - DomainKeys Identified Mail (**DKIM**) Signatures (_RFC 6376_) with ED25519-SHA256, RSA-SHA256 and RSA-SHA1 support. - Simple Mail Transfer Protocol (**SMTP**; _RFC 5321_) delivery. - SMTP Service Extension for Secure SMTP over **TLS** (_RFC 3207_). - SMTP Service Extension for Authentication (_RFC 4954_) with automatic mechanism negotiation (from most secure to least secure): - CRAM-MD5 (_RFC 2195_) - DIGEST-MD5 (_RFC 2831_; obsolete but still supported) - XOAUTH2 (Google proprietary) - LOGIN - PLAIN - Full async (requires Tokio). ## Usage Example Send a message via an SMTP server that requires authentication: ```rust // Build a simple multipart message let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to(vec![ ("Jane Doe", "jane@example.com"), ("James Smith", "james@test.com"), ]) .subject("Hi!") .html_body("

Hello, world!

") .text_body("Hello world!"); // Connect to the SMTP submissions port, upgrade to TLS and // authenticate using the provided credentials. SmtpClientBuilder::new("smtp.gmail.com", 587) .implicit_tls(false) .credentials(("john", "p4ssw0rd")) .connect() .await .unwrap() .send(message) .await .unwrap(); ``` Sign a message with DKIM and send it via an SMTP relay server: ```rust // Build a simple text message with a single attachment let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to("jane@example.com") .subject("Howdy!") .text_body("These pretzels are making me thirsty.") .attachment("image/png", "pretzels.png", [1, 2, 3, 4].as_ref()); // Sign an e-mail message using RSA-SHA256 let pk_rsa = RsaKey::::from_rsa_pem(TEST_KEY).unwrap(); let signer = DkimSigner::from_key(pk_rsa) .domain("example.com") .selector("default") .headers(["From", "To", "Subject"]) .expiration(60 * 60 * 7); // Number of seconds before this signature expires (optional) // Connect to an SMTP relay server over TLS. // Signs each message with the configured DKIM signer. SmtpClientBuilder::new("smtp.gmail.com", 465) .connect() .await .unwrap() .send_signed(message, &signer) .await .unwrap(); ``` More examples of how to build messages are available in the [`mail-builder`](https://crates.io/crates/mail-builder) crate. Please note that this library does not support parsing e-mail messages as this functionality is provided separately by the [`mail-parser`](https://crates.io/crates/mail-parser) crate. ## Testing To run the testsuite: ```bash $ cargo test --all-features ``` or, to run the testsuite with MIRI: ```bash $ cargo +nightly miri test --all-features ``` ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Copyright Copyright (C) 2020-2022, Stalwart Labs Ltd. mail-send-0.5.0/examples/000077500000000000000000000000001474544475200152235ustar00rootroot00000000000000mail-send-0.5.0/examples/smtp_auth.rs000066400000000000000000000025131474544475200175760ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use mail_builder::MessageBuilder; use mail_send::SmtpClientBuilder; #[tokio::main] async fn main() { // Build a simple multipart message // More examples of how to build messages available at // https://github.com/stalwartlabs/mail-builder/tree/main/examples let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to(vec![ ("Jane Doe", "jane@example.com"), ("James Smith", "james@test.com"), ]) .subject("Hi!") .html_body("

Hello, world!

") .text_body("Hello world!"); // Connect to the SMTP submissions port, upgrade to TLS and // authenticate using the provided credentials. SmtpClientBuilder::new("smtp.gmail.com", 587) .implicit_tls(false) .credentials(("john", "p4ssw0rd")) .connect() .await .unwrap() .send(message) .await .unwrap(); } mail-send-0.5.0/examples/smtp_dkim.rs000066400000000000000000000051171474544475200175640ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use mail_auth::{ common::crypto::{RsaKey, Sha256}, dkim::DkimSigner, }; use mail_builder::MessageBuilder; use mail_send::SmtpClientBuilder; const TEST_KEY: &str = r#"-----BEGIN RSA PRIVATE KEY----- MIICXwIBAAKBgQDwIRP/UC3SBsEmGqZ9ZJW3/DkMoGeLnQg1fWn7/zYtIxN2SnFC jxOCKG9v3b4jYfcTNh5ijSsq631uBItLa7od+v/RtdC2UzJ1lWT947qR+Rcac2gb to/NMqJ0fzfVjH4OuKhitdY9tf6mcwGjaNBcWToIMmPSPDdQPNUYckcQ2QIDAQAB AoGBALmn+XwWk7akvkUlqb+dOxyLB9i5VBVfje89Teolwc9YJT36BGN/l4e0l6QX /1//6DWUTB3KI6wFcm7TWJcxbS0tcKZX7FsJvUz1SbQnkS54DJck1EZO/BLa5ckJ gAYIaqlA9C0ZwM6i58lLlPadX/rtHb7pWzeNcZHjKrjM461ZAkEA+itss2nRlmyO n1/5yDyCluST4dQfO8kAB3toSEVc7DeFeDhnC1mZdjASZNvdHS4gbLIA1hUGEF9m 3hKsGUMMPwJBAPW5v/U+AWTADFCS22t72NUurgzeAbzb1HWMqO4y4+9Hpjk5wvL/ eVYizyuce3/fGke7aRYw/ADKygMJdW8H/OcCQQDz5OQb4j2QDpPZc0Nc4QlbvMsj 7p7otWRO5xRa6SzXqqV3+F0VpqvDmshEBkoCydaYwc2o6WQ5EBmExeV8124XAkEA qZzGsIxVP+sEVRWZmW6KNFSdVUpk3qzK0Tz/WjQMe5z0UunY9Ax9/4PVhp/j61bf eAYXunajbBSOLlx4D+TunwJBANkPI5S9iylsbLs6NkaMHV6k5ioHBBmgCak95JGX GMot/L2x0IYyMLAz6oLWh2hm7zwtb0CgOrPo1ke44hFYnfc= -----END RSA PRIVATE KEY-----"#; #[tokio::main] async fn main() { // Build a simple text message with a single attachment // More examples of how to build messages available at // https://github.com/stalwartlabs/mail-builder/tree/main/examples let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to("jane@example.com") .subject("Howdy!") .text_body("These pretzels are making me thirsty.") .attachment("image/png", "pretzels.png", [1, 2, 3, 4].as_ref()); // Sign an e-mail message using RSA-SHA256 let pk_rsa = RsaKey::::from_rsa_pem(TEST_KEY).unwrap(); let signer = DkimSigner::from_key(pk_rsa) .domain("example.com") .selector("default") .headers(["From", "To", "Subject"]) .expiration(60 * 60 * 7); // Number of seconds before this signature expires (optional) // Connect to an SMTP relay server over TLS. // Signs each message with the configured DKIM signer. SmtpClientBuilder::new("smtp.gmail.com", 465) .connect() .await .unwrap() .send_signed(message, &signer) .await .unwrap(); } mail-send-0.5.0/examples/smtp_raw_message.rs000066400000000000000000000021131474544475200211260ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use mail_send::smtp::message::Message; use mail_send::SmtpClientBuilder; #[tokio::main] async fn main() { // Build a raw message let message = Message::empty() .from("jdoe@example.com") .to("jane@example.com") .to("james@smith.com") .body(&b"From: jdoe@example.com\nTo: jane@example.com\nSubject: Hi!\n\nHello, world!"[..]); // Connect to an SMTP relay server. // The library will upgrade the connection to TLS if the server supports it. SmtpClientBuilder::new("mail.smtp2go.com", 2525) .implicit_tls(false) .connect() .await .unwrap() .send(message) .await .unwrap(); } mail-send-0.5.0/examples/smtp_relay.rs000066400000000000000000000024071474544475200177530ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use mail_builder::MessageBuilder; use mail_send::SmtpClientBuilder; #[tokio::main] async fn main() { // Build a simple text message with a single attachment // More examples of how to build messages available at // https://github.com/stalwartlabs/mail-builder/tree/main/examples let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to("jane@example.com") .subject("Hello, world!") .text_body("Hello, world!") .attachment("image/png", "kittens.png", [1, 2, 3, 4].as_ref()); // Connect to an SMTP relay server. // The library will upgrade the connection to TLS if the server supports it. SmtpClientBuilder::new("mail.smtp2go.com", 2525) .implicit_tls(false) .connect() .await .unwrap() .send(message) .await .unwrap(); } mail-send-0.5.0/examples/smtp_tls_relay.rs000066400000000000000000000022471474544475200206370ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use mail_builder::MessageBuilder; use mail_send::SmtpClientBuilder; #[tokio::main] async fn main() { // Build a simple html message with a single attachment // More examples of how to build messages available at // https://github.com/stalwartlabs/mail-builder/tree/main/examples let message = MessageBuilder::new() .from(("John Doe", "john@example.com")) .to("jane@example.com") .subject("Hello, world!") .html_body("

Hello, world!

") .attachment("image/png", "kittens.png", [1, 2, 3, 4].as_ref()); // Connect to an SMTP relay server over TLS SmtpClientBuilder::new("smtp.gmail.com", 465) .connect() .await .unwrap() .send(message) .await .unwrap(); } mail-send-0.5.0/src/000077500000000000000000000000001474544475200141745ustar00rootroot00000000000000mail-send-0.5.0/src/lib.rs000066400000000000000000000211741474544475200153150ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ //! # mail-send //! //! [![crates.io](https://img.shields.io/crates/v/mail-send)](https://crates.io/crates/mail-send) //! [![build](https://github.com/stalwartlabs/mail-send/actions/workflows/rust.yml/badge.svg)](https://github.com/stalwartlabs/mail-send/actions/workflows/rust.yml) //! [![docs.rs](https://img.shields.io/docsrs/mail-send)](https://docs.rs/mail-send) //! [![crates.io](https://img.shields.io/crates/l/mail-send)](http://www.apache.org/licenses/LICENSE-2.0) //! //! _mail-send_ is a Rust library to build, sign and send e-mail messages via SMTP. It includes the following features: //! //! - Generates **e-mail** messages conforming to the Internet Message Format standard (_RFC 5322_). //! - Full **MIME** support (_RFC 2045 - 2049_) with automatic selection of the most optimal encoding for each message body part. //! - DomainKeys Identified Mail (**DKIM**) Signatures (_RFC 6376_) with ED25519-SHA256, RSA-SHA256 and RSA-SHA1 support. //! - Simple Mail Transfer Protocol (**SMTP**; _RFC 5321_) delivery. //! - SMTP Service Extension for Secure SMTP over **TLS** (_RFC 3207_). //! - SMTP Service Extension for Authentication (_RFC 4954_) with automatic mechanism negotiation (from most secure to least secure): //! - CRAM-MD5 (_RFC 2195_) //! - DIGEST-MD5 (_RFC 2831_; obsolete but still supported) //! - XOAUTH2 (Google proprietary) //! - LOGIN //! - PLAIN //! - Full async (requires Tokio). //! //! ## Usage Example //! //! Send a message via an SMTP server that requires authentication: //! //! ```rust //! // Build a simple multipart message //! let message = MessageBuilder::new() //! .from(("John Doe", "john@example.com")) //! .to(vec![ //! ("Jane Doe", "jane@example.com"), //! ("James Smith", "james@test.com"), //! ]) //! .subject("Hi!") //! .html_body("

Hello, world!

") //! .text_body("Hello world!"); //! //! // Connect to the SMTP submissions port, upgrade to TLS and //! // authenticate using the provided credentials. //! SmtpClientBuilder::new("smtp.gmail.com", 587) //! .implicit_tls(false) //! .credentials(("john", "p4ssw0rd")) //! .connect() //! .await //! .unwrap() //! .send(message) //! .await //! .unwrap(); //! ``` //! //! Sign a message with DKIM and send it via an SMTP relay server: //! //! ```rust //! // Build a simple text message with a single attachment //! let message = MessageBuilder::new() //! .from(("John Doe", "john@example.com")) //! .to("jane@example.com") //! .subject("Howdy!") //! .text_body("These pretzels are making me thirsty.") //! .attachment("image/png", "pretzels.png", [1, 2, 3, 4].as_ref()); //! //! // Sign an e-mail message using RSA-SHA256 //! let pk_rsa = RsaKey::::from_rsa_pem(TEST_KEY).unwrap(); //! let signer = DkimSigner::from_key(pk_rsa) //! .domain("example.com") //! .selector("default") //! .headers(["From", "To", "Subject"]) //! .expiration(60 * 60 * 7); // Number of seconds before this signature expires (optional) //! //! // Connect to an SMTP relay server over TLS. //! // Signs each message with the configured DKIM signer. //! SmtpClientBuilder::new("smtp.gmail.com", 465) //! .connect() //! .await //! .unwrap() //! .send_signed(message, &signer) //! .await //! .unwrap(); //! ``` //! //! More examples of how to build messages are available in the [`mail-builder`](https://crates.io/crates/mail-builder) crate. //! Please note that this library does not support parsing e-mail messages as this functionality is provided separately by the [`mail-parser`](https://crates.io/crates/mail-parser) crate. //! //! ## Testing //! //! To run the testsuite: //! //! ```bash //! $ cargo test --all-features //! ``` //! //! or, to run the testsuite with MIRI: //! //! ```bash //! $ cargo +nightly miri test --all-features //! ``` //! //! ## License //! //! Licensed under either of //! //! * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) //! * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) //! //! at your option. //! //! ## Copyright //! //! Copyright (C) 2020-2022, Stalwart Labs Ltd. //! //! See [COPYING] for the license. //! //! [COPYING]: https://github.com/stalwartlabs/mail-send/blob/main/COPYING //! pub mod smtp; use std::{fmt::Display, hash::Hash, time::Duration}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_rustls::TlsConnector; #[cfg(feature = "builder")] pub use mail_builder; #[cfg(feature = "dkim")] pub use mail_auth; #[derive(Debug)] pub enum Error { /// I/O error Io(std::io::Error), /// TLS error Tls(Box), /// Base64 decode error Base64(base64::DecodeError), // SMTP authentication error. Auth(smtp::auth::Error), /// Failure parsing SMTP reply UnparseableReply, /// Unexpected SMTP reply. UnexpectedReply(smtp_proto::Response), /// SMTP authentication failure. AuthenticationFailed(smtp_proto::Response), /// Invalid TLS name provided. InvalidTLSName, /// Missing authentication credentials. MissingCredentials, /// Missing message sender. MissingMailFrom, /// Missing message recipients. MissingRcptTo, /// The server does no support any of the available authentication methods. UnsupportedAuthMechanism, /// Connection timeout. Timeout, /// STARTTLS not available MissingStartTls, } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Io(ref err) => err.source(), Error::Tls(ref err) => err.source(), Error::Base64(ref err) => err.source(), _ => None, } } } pub type Result = std::result::Result; /// SMTP client builder #[derive(Clone)] pub struct SmtpClientBuilder + PartialEq + Eq + Hash> { pub timeout: Duration, pub tls_connector: TlsConnector, pub tls_hostname: T, pub tls_implicit: bool, pub credentials: Option>, pub addr: String, pub is_lmtp: bool, pub say_ehlo: bool, pub local_host: String, } /// SMTP client builder pub struct SmtpClient { pub stream: T, pub timeout: Duration, } #[derive(Clone, PartialEq, Eq, Hash)] pub enum Credentials + PartialEq + Eq + Hash> { Plain { username: T, secret: T }, OAuthBearer { token: T }, XOauth2 { username: T, secret: T }, } impl Default for Credentials { fn default() -> Self { Credentials::Plain { username: String::new(), secret: String::new(), } } } impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Io(e) => write!(f, "I/O error: {e}"), Error::Tls(e) => write!(f, "TLS error: {e}"), Error::Base64(e) => write!(f, "Base64 decode error: {e}"), Error::Auth(e) => write!(f, "SMTP authentication error: {e}"), Error::UnparseableReply => write!(f, "Unparseable SMTP reply"), Error::UnexpectedReply(e) => write!(f, "Unexpected reply: {e}"), Error::AuthenticationFailed(e) => write!(f, "Authentication failed: {e}"), Error::InvalidTLSName => write!(f, "Invalid TLS name provided"), Error::MissingCredentials => write!(f, "Missing authentication credentials"), Error::MissingMailFrom => write!(f, "Missing message sender"), Error::MissingRcptTo => write!(f, "Missing message recipients"), Error::UnsupportedAuthMechanism => write!( f, "The server does no support any of the available authentication methods" ), Error::Timeout => write!(f, "Connection timeout"), Error::MissingStartTls => write!(f, "STARTTLS extension unavailable"), } } } impl From for Error { fn from(err: std::io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: base64::DecodeError) -> Self { Error::Base64(err) } } mail-send-0.5.0/src/smtp/000077500000000000000000000000001474544475200151575ustar00rootroot00000000000000mail-send-0.5.0/src/smtp/auth.rs000066400000000000000000000367771474544475200165120ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use std::{fmt::Display, hash::Hash}; use base64::{engine, Engine}; use smtp_proto::{ response::generate::BitToString, EhloResponse, AUTH_CRAM_MD5, AUTH_DIGEST_MD5, AUTH_LOGIN, AUTH_OAUTHBEARER, AUTH_PLAIN, AUTH_XOAUTH2, }; use tokio::io::{AsyncRead, AsyncWrite}; use crate::{Credentials, SmtpClient}; impl SmtpClient { pub async fn authenticate( &mut self, credentials: impl AsRef>, capabilities: impl AsRef>, ) -> crate::Result<&mut Self> where U: AsRef + PartialEq + Eq + Hash, { let credentials = credentials.as_ref(); let capabilities = capabilities.as_ref(); let mut available_mechanisms = match &credentials { Credentials::Plain { .. } => AUTH_CRAM_MD5 | AUTH_DIGEST_MD5 | AUTH_LOGIN | AUTH_PLAIN, Credentials::OAuthBearer { .. } => AUTH_OAUTHBEARER, Credentials::XOauth2 { .. } => AUTH_XOAUTH2, } & capabilities.auth_mechanisms; // Try authenticating from most secure to least secure let mut has_err = None; let mut has_failed = false; while available_mechanisms != 0 && !has_failed { let mechanism = 1 << ((63 - available_mechanisms.leading_zeros()) as u64); available_mechanisms ^= mechanism; match self.auth(mechanism, credentials).await { Ok(_) => { return Ok(self); } Err(err) => match err { crate::Error::UnexpectedReply(reply) => { has_failed = reply.code() == 535; has_err = reply.into(); } crate::Error::UnsupportedAuthMechanism => (), _ => return Err(err), }, } } if let Some(has_err) = has_err { Err(crate::Error::AuthenticationFailed(has_err)) } else { Err(crate::Error::UnsupportedAuthMechanism) } } pub(crate) async fn auth( &mut self, mechanism: u64, credentials: &Credentials, ) -> crate::Result<()> where U: AsRef + PartialEq + Eq + Hash, { let mut reply = if (mechanism & (AUTH_PLAIN | AUTH_XOAUTH2 | AUTH_OAUTHBEARER)) != 0 { self.cmd( format!( "AUTH {} {}\r\n", mechanism.to_mechanism(), credentials.encode(mechanism, "")?, ) .as_bytes(), ) .await? } else { self.cmd(format!("AUTH {}\r\n", mechanism.to_mechanism()).as_bytes()) .await? }; for _ in 0..3 { match reply.code() { 334 => { reply = self .cmd( format!("{}\r\n", credentials.encode(mechanism, reply.message())?) .as_bytes(), ) .await?; } 235 => { return Ok(()); } _ => { return Err(crate::Error::UnexpectedReply(reply)); } } } Err(crate::Error::UnexpectedReply(reply)) } } #[derive(Debug, Clone)] pub enum Error { InvalidChallenge, } impl + PartialEq + Eq + Hash> Credentials { /// Creates a new `Credentials` instance. pub fn new(username: T, secret: T) -> Credentials { Credentials::Plain { username, secret } } /// Creates a new XOAuth2 `Credentials` instance. pub fn new_xoauth2(username: T, secret: T) -> Credentials { Credentials::XOauth2 { username, secret } } /// Creates a new OAuthBearer `Credentials` instance. pub fn new_oauth(payload: T) -> Credentials { Credentials::OAuthBearer { token: payload } } /// Creates a new OAuthBearer `Credentials` instance from a Bearer token. pub fn new_oauth_from_token(token: T) -> Credentials { Credentials::OAuthBearer { token: format!("auth=Bearer {}\x01\x01", token.as_ref()), } } pub fn encode(&self, mechanism: u64, challenge: &str) -> crate::Result { Ok(engine::general_purpose::STANDARD.encode( match (mechanism, self) { (AUTH_PLAIN, Credentials::Plain { username, secret }) => { format!("\u{0}{}\u{0}{}", username.as_ref(), secret.as_ref()) } (AUTH_LOGIN, Credentials::Plain { username, secret }) => { let challenge = engine::general_purpose::STANDARD.decode(challenge)?; let username = username.as_ref(); let secret = secret.as_ref(); if b"user name" .eq_ignore_ascii_case(challenge.get(0..9).ok_or(Error::InvalidChallenge)?) || b"username".eq_ignore_ascii_case( // Because Google makes its own standards challenge.get(0..8).ok_or(Error::InvalidChallenge)?, ) { &username } else if b"password" .eq_ignore_ascii_case(challenge.get(0..8).ok_or(Error::InvalidChallenge)?) { &secret } else { return Err(Error::InvalidChallenge.into()); } .to_string() } #[cfg(feature = "digest-md5")] (AUTH_DIGEST_MD5, Credentials::Plain { username, secret }) => { let mut buf = Vec::with_capacity(10); let mut key = None; let mut in_quote = false; let mut values = std::collections::HashMap::new(); let challenge = engine::general_purpose::STANDARD.decode(challenge)?; let challenge_len = challenge.len(); let username = username.as_ref(); let secret = secret.as_ref(); for (pos, byte) in challenge.into_iter().enumerate() { let add_key = match byte { b'=' if !in_quote => { if key.is_none() && !buf.is_empty() { key = String::from_utf8_lossy(&buf).into_owned().into(); buf.clear(); } else { return Err(Error::InvalidChallenge.into()); } false } b',' if !in_quote => true, b'"' => { in_quote = !in_quote; false } _ => { buf.push(byte); false } }; if (add_key || pos == challenge_len - 1) && key.is_some() && !buf.is_empty() { values.insert( key.take().unwrap(), String::from_utf8_lossy(&buf).into_owned(), ); buf.clear(); } } let (digest_uri, realm, realm_response) = if let Some(realm) = values.get("realm") { ( format!("smtp/{realm}"), realm.as_str(), format!(",realm=\"{realm}\""), ) } else { ("smtp/localhost".to_string(), "", "".to_string()) }; let credentials = md5::compute(format!("{username}:{realm}:{secret}").as_bytes()); let a2 = md5::compute( if values.get("qpop").is_some_and(|v| v == "auth") { format!("AUTHENTICATE:{digest_uri}") } else { format!("AUTHENTICATE:{digest_uri}:00000000000000000000000000000000") } .as_bytes(), ); #[allow(unused_variables)] let cnonce = { use rand::RngCore; let mut buf = [0u8; 16]; rand::thread_rng().fill_bytes(&mut buf); engine::general_purpose::STANDARD.encode(buf) }; #[cfg(test)] let cnonce = "OA6MHXh6VqTrRk".to_string(); let nonce = values.remove("nonce").unwrap_or_default(); let qop = values.remove("qop").unwrap_or_default(); let charset = values .remove("charset") .unwrap_or_else(|| "utf-8".to_string()); format!( concat!( "charset={},username=\"{}\",realm=\"{}\",nonce=\"{}\",nc=00000001,", "cnonce=\"{}\",digest-uri=\"{}\",response={:x},qop={}" ), charset, username, realm_response, nonce, cnonce, digest_uri, md5::compute( format!("{credentials:x}:{nonce}:00000001:{cnonce}:{qop}:{a2:x}") .as_bytes() ), qop ) } #[cfg(feature = "cram-md5")] (AUTH_CRAM_MD5, Credentials::Plain { username, secret }) => { let mut secret_opad: Vec = vec![0x5c; 64]; let mut secret_ipad: Vec = vec![0x36; 64]; let username = username.as_ref(); let secret = secret.as_ref(); if secret.len() < 64 { for (pos, byte) in secret.as_bytes().iter().enumerate() { secret_opad[pos] = *byte ^ 0x5c; secret_ipad[pos] = *byte ^ 0x36; } } else { for (pos, byte) in md5::compute(secret.as_bytes()).iter().enumerate() { secret_opad[pos] = *byte ^ 0x5c; secret_ipad[pos] = *byte ^ 0x36; } } secret_ipad .extend_from_slice(&engine::general_purpose::STANDARD.decode(challenge)?); secret_opad.extend_from_slice(&md5::compute(&secret_ipad).0); format!("{} {:x}", username, md5::compute(&secret_opad)) } (AUTH_XOAUTH2, Credentials::XOauth2 { username, secret }) => format!( "user={}\x01auth=Bearer {}\x01\x01", username.as_ref(), secret.as_ref() ), (AUTH_OAUTHBEARER, Credentials::OAuthBearer { token }) => { token.as_ref().to_string() } _ => return Err(crate::Error::UnsupportedAuthMechanism), } .as_bytes(), )) } } impl<'x> From<(&'x str, &'x str)> for Credentials<&'x str> { fn from(credentials: (&'x str, &'x str)) -> Self { Credentials::Plain { username: credentials.0, secret: credentials.1, } } } impl From<(String, String)> for Credentials { fn from(credentials: (String, String)) -> Self { Credentials::Plain { username: credentials.0, secret: credentials.1, } } } impl + PartialEq + Eq + Hash> AsRef> for Credentials { fn as_ref(&self) -> &Credentials { self } } impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::InvalidChallenge => write!(f, "Invalid challenge received."), } } } #[cfg(test)] mod test { use smtp_proto::{AUTH_CRAM_MD5, AUTH_DIGEST_MD5, AUTH_LOGIN, AUTH_PLAIN, AUTH_XOAUTH2}; use crate::smtp::auth::Credentials; #[test] fn auth_encode() { // Digest-MD5 #[cfg(feature = "digest-md5")] assert_eq!( Credentials::new("chris", "secret") .encode( AUTH_DIGEST_MD5, concat!( "cmVhbG09ImVsd29vZC5pbm5vc29mdC5jb20iLG5vbmNlPSJPQTZNRzl0", "RVFHbTJoaCIscW9wPSJhdXRoIixhbGdvcml0aG09bWQ1LXNlc3MsY2hh", "cnNldD11dGYtOA==" ), ) .unwrap(), concat!( "Y2hhcnNldD11dGYtOCx1c2VybmFtZT0iY2hyaXMiLHJlYWxtPSIscmVhbG0", "9ImVsd29vZC5pbm5vc29mdC5jb20iIixub25jZT0iT0E2TUc5dEVRR20yaG", "giLG5jPTAwMDAwMDAxLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLGRpZ2Vzd", "C11cmk9InNtdHAvZWx3b29kLmlubm9zb2Z0LmNvbSIscmVzcG9uc2U9NDQ2", "NjIxODg3MzlmYzcxOGNlYmYyZjA4MTk4MWI4ZDIscW9wPWF1dGg=", ) ); // Challenge-Response Authentication Mechanism (CRAM) #[cfg(feature = "cram-md5")] assert_eq!( Credentials::new("tim", "tanstaaftanstaaf") .encode( AUTH_CRAM_MD5, "PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+", ) .unwrap(), "dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw" ); // SASL XOAUTH2 assert_eq!( Credentials::XOauth2 { username: "someuser@example.com", secret: "ya29.vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg" } .encode(AUTH_XOAUTH2, "",) .unwrap(), concat!( "dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5Ln", "ZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==" ) ); // Login assert_eq!( Credentials::new("tim", "tanstaaftanstaaf") .encode(AUTH_LOGIN, "VXNlciBOYW1lAA==",) .unwrap(), "dGlt" ); assert_eq!( Credentials::new("tim", "tanstaaftanstaaf") .encode(AUTH_LOGIN, "UGFzc3dvcmQA",) .unwrap(), "dGFuc3RhYWZ0YW5zdGFhZg==" ); // Plain assert_eq!( Credentials::new("tim", "tanstaaftanstaaf") .encode(AUTH_PLAIN, "",) .unwrap(), "AHRpbQB0YW5zdGFhZnRhbnN0YWFm" ); } } mail-send-0.5.0/src/smtp/builder.rs000066400000000000000000000124621474544475200171600ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use smtp_proto::{EhloResponse, EXT_START_TLS}; use std::hash::Hash; use std::time::Duration; use tokio::{ io::{AsyncRead, AsyncWrite}, net::TcpStream, }; use tokio_rustls::client::TlsStream; use crate::{Credentials, SmtpClient, SmtpClientBuilder}; use super::{tls::build_tls_connector, AssertReply}; impl + PartialEq + Eq + Hash> SmtpClientBuilder { pub fn new(hostname: T, port: u16) -> Self { SmtpClientBuilder { addr: format!("{}:{}", hostname.as_ref(), port), timeout: Duration::from_secs(60 * 60), tls_connector: build_tls_connector(false), tls_hostname: hostname, tls_implicit: true, is_lmtp: false, local_host: gethostname::gethostname() .to_str() .unwrap_or("[127.0.0.1]") .to_string(), credentials: None, say_ehlo: true, } } /// Allow invalid TLS certificates pub fn allow_invalid_certs(mut self) -> Self { self.tls_connector = build_tls_connector(true); self } /// Start connection in TLS or upgrade with STARTTLS pub fn implicit_tls(mut self, tls_implicit: bool) -> Self { self.tls_implicit = tls_implicit; self } /// Use LMTP instead of SMTP pub fn lmtp(mut self, is_lmtp: bool) -> Self { self.is_lmtp = is_lmtp; self } // Say EHLO/LHLO pub fn say_ehlo(mut self, say_ehlo: bool) -> Self { self.say_ehlo = say_ehlo; self } /// Set the EHLO/LHLO hostname pub fn helo_host(mut self, host: impl Into) -> Self { self.local_host = host.into(); self } /// Sets the authentication credentials pub fn credentials(mut self, credentials: impl Into>) -> Self { self.credentials = Some(credentials.into()); self } /// Sets the SMTP connection timeout pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = timeout; self } /// Connect over TLS pub async fn connect(&self) -> crate::Result>> { tokio::time::timeout(self.timeout, async { let mut client = SmtpClient { stream: TcpStream::connect(&self.addr).await?, timeout: self.timeout, }; let mut client = if self.tls_implicit { let mut client = client .into_tls(&self.tls_connector, self.tls_hostname.as_ref()) .await?; // Read greeting client.read().await?.assert_positive_completion()?; client } else { // Read greeting client.read().await?.assert_positive_completion()?; // Send EHLO let response = if !self.is_lmtp { client.ehlo(&self.local_host).await? } else { client.lhlo(&self.local_host).await? }; if response.has_capability(EXT_START_TLS) { client .start_tls(&self.tls_connector, self.tls_hostname.as_ref()) .await? } else { return Err(crate::Error::MissingStartTls); } }; if self.say_ehlo { // Obtain capabilities let capabilities = client.capabilities(&self.local_host, self.is_lmtp).await?; // Authenticate if let Some(credentials) = &self.credentials { client.authenticate(&credentials, &capabilities).await?; } } Ok(client) }) .await .map_err(|_| crate::Error::Timeout)? } /// Connect over clear text (should not be used) pub async fn connect_plain(&self) -> crate::Result> { let mut client = SmtpClient { stream: tokio::time::timeout(self.timeout, async { TcpStream::connect(&self.addr).await }) .await .map_err(|_| crate::Error::Timeout)??, timeout: self.timeout, }; // Read greeting client.read().await?.assert_positive_completion()?; if self.say_ehlo { // Obtain capabilities let capabilities = client.capabilities(&self.local_host, self.is_lmtp).await?; // Authenticate if let Some(credentials) = &self.credentials { client.authenticate(&credentials, &capabilities).await?; } } Ok(client) } } impl SmtpClient { pub async fn capabilities( &mut self, local_host: &str, is_lmtp: bool, ) -> crate::Result> { if !is_lmtp { self.ehlo(local_host).await } else { self.lhlo(local_host).await } } } mail-send-0.5.0/src/smtp/client.rs000066400000000000000000000223271474544475200170110ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use std::{ net::{IpAddr, SocketAddr}, time::Duration, }; use smtp_proto::{response::parser::ResponseReceiver, Response}; use tokio::{ io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, net::{TcpSocket, TcpStream}, }; use crate::SmtpClient; impl SmtpClient { pub async fn read(&mut self) -> crate::Result> { let mut buf = vec![0u8; 1024]; let mut parser = ResponseReceiver::default(); loop { let br = self.stream.read(&mut buf).await?; if br > 0 { match parser.parse(&mut buf[..br].iter()) { Ok(reply) => return Ok(reply), Err(err) => match err { smtp_proto::Error::NeedsMoreData { .. } => (), _ => { return Err(crate::Error::UnparseableReply); } }, } } else { return Err(crate::Error::UnparseableReply); } } } pub async fn read_many(&mut self, num: usize) -> crate::Result>> { let mut buf = vec![0u8; 1024]; let mut response = Vec::with_capacity(num); let mut parser = ResponseReceiver::default(); 'outer: loop { let br = self.stream.read(&mut buf).await?; if br > 0 { let mut iter = buf[..br].iter(); loop { match parser.parse(&mut iter) { Ok(reply) => { response.push(reply); if response.len() != num { parser.reset(); } else { break 'outer; } } Err(err) => match err { smtp_proto::Error::NeedsMoreData { .. } => break, _ => { return Err(crate::Error::UnparseableReply); } }, } } } else { return Err(crate::Error::UnparseableReply); } } Ok(response) } /// Sends a command to the SMTP server and waits for a reply. pub async fn cmd(&mut self, cmd: impl AsRef<[u8]>) -> crate::Result> { tokio::time::timeout(self.timeout, async { self.stream.write_all(cmd.as_ref()).await?; self.stream.flush().await?; self.read().await }) .await .map_err(|_| crate::Error::Timeout)? } /// Pipelines multiple command to the SMTP server and waits for a reply. pub async fn cmds( &mut self, cmds: impl IntoIterator>, ) -> crate::Result>> { tokio::time::timeout(self.timeout, async { let mut num_replies = 0; for cmd in cmds { self.stream.write_all(cmd.as_ref()).await?; num_replies += 1; } self.stream.flush().await?; self.read_many(num_replies).await }) .await .map_err(|_| crate::Error::Timeout)? } } impl SmtpClient { /// Connects to a remote host address pub async fn connect(remote_addr: SocketAddr, timeout: Duration) -> crate::Result { tokio::time::timeout(timeout, async { Ok(SmtpClient { stream: TcpStream::connect(remote_addr).await?, timeout, }) }) .await .map_err(|_| crate::Error::Timeout)? } /// Connects to a remote host address using the provided local IP pub async fn connect_using( local_ip: IpAddr, remote_addr: SocketAddr, timeout: Duration, ) -> crate::Result { tokio::time::timeout(timeout, async { let socket = if local_ip.is_ipv4() { TcpSocket::new_v4()? } else { TcpSocket::new_v6()? }; socket.bind(SocketAddr::new(local_ip, 0))?; Ok(SmtpClient { stream: socket.connect(remote_addr).await?, timeout, }) }) .await .map_err(|_| crate::Error::Timeout)? } } #[cfg(test)] mod test { use std::time::Duration; use tokio::io::{AsyncRead, AsyncWrite}; use crate::{SmtpClient, SmtpClientBuilder}; #[tokio::test] async fn smtp_basic() { // StartTLS test env_logger::init(); let client = SmtpClientBuilder::new("mail.smtp2go.com", 2525) .implicit_tls(false) .connect() .await .unwrap(); client.quit().await.unwrap(); let client = SmtpClientBuilder::new("mail.smtp2go.com", 2525) .allow_invalid_certs() .implicit_tls(false) .connect() .await .unwrap(); client.quit().await.unwrap(); // Say hello to Google over TLS and quit let client = SmtpClientBuilder::new("smtp.gmail.com", 465) .connect() .await .unwrap(); client.quit().await.unwrap(); // Say hello to Google over TLS and quit let client = SmtpClientBuilder::new("smtp.gmail.com", 465) .allow_invalid_certs() .connect() .await .unwrap(); client.quit().await.unwrap(); } #[derive(Default)] struct AsyncBufWriter { buf: Vec, } impl AsyncRead for AsyncBufWriter { fn poll_read( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, _buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll> { unreachable!() } } impl AsyncWrite for AsyncBufWriter { fn poll_write( mut self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, buf: &[u8], ) -> std::task::Poll> { self.buf.extend_from_slice(buf); std::task::Poll::Ready(Ok(buf.len())) } fn poll_flush( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll> { std::task::Poll::Ready(Ok(())) } fn poll_shutdown( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll> { std::task::Poll::Ready(Ok(())) } } #[tokio::test] async fn transparency_procedure() { const SMUGGLER: &str = r#"From: Joe SixPack To: Suzie Q Subject: Is dinner ready? Hi. We lost the game. Are you hungry yet? Joe. . MAIL FROM: RCPT TO: DATA From: Joe SixPack To: Suzie Q Subject: smuggled message This is a smuggled message "#; for (test, result) in [ ( "A: b\r\n.\r\n".to_string(), "A: b\r\n..\r\n\r\n.\r\n".to_string(), ), ("A: b\r\n.".to_string(), "A: b\r\n..\r\n.\r\n".to_string()), ( "A: b\r\n..\r\n".to_string(), "A: b\r\n...\r\n\r\n.\r\n".to_string(), ), ("A: ...b".to_string(), "A: ...b\r\n.\r\n".to_string()), ( "A: \n.\r\nMAIL FROM:<>".to_string(), "A: \n..\r\nMAIL FROM:<>\r\n.\r\n".to_string(), ), ( "A: \r.\r\nMAIL FROM:<>".to_string(), "A: \r..\r\nMAIL FROM:<>\r\n.\r\n".to_string(), ), ( SMUGGLER .replace('\r', "") .replace('\n', "\r\n") .replace("", "\r"), SMUGGLER .replace('\r', "") .replace('\n', "\r\n") .replace("", "\r.") + "\r\n.\r\n", ), ( SMUGGLER .replace('\r', "") .replace('\n', "\r\n") .replace("", "\n"), SMUGGLER .replace('\r', "") .replace('\n', "\r\n") .replace("", "\n.") + "\r\n.\r\n", ), ] { let mut client = SmtpClient { stream: AsyncBufWriter::default(), timeout: Duration::from_secs(30), }; client.write_message(test.as_bytes()).await.unwrap(); assert_eq!(String::from_utf8(client.stream.buf).unwrap(), result); } } } mail-send-0.5.0/src/smtp/ehlo.rs000066400000000000000000000065611474544475200164640ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use smtp_proto::{ response::parser::{ResponseReceiver, MAX_RESPONSE_LENGTH}, EhloResponse, }; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use crate::SmtpClient; impl SmtpClient { /// Sends a EHLO command to the server. pub async fn ehlo(&mut self, hostname: &str) -> crate::Result> { tokio::time::timeout(self.timeout, async { self.stream .write_all(format!("EHLO {hostname}\r\n").as_bytes()) .await?; self.stream.flush().await?; self.read_ehlo().await }) .await .map_err(|_| crate::Error::Timeout)? } /// Sends a LHLO command to the server. pub async fn lhlo(&mut self, hostname: &str) -> crate::Result> { tokio::time::timeout(self.timeout, async { self.stream .write_all(format!("LHLO {hostname}\r\n").as_bytes()) .await?; self.stream.flush().await?; self.read_ehlo().await }) .await .map_err(|_| crate::Error::Timeout)? } pub async fn read_ehlo(&mut self) -> crate::Result> { let mut buf = vec![0u8; 1024]; let mut buf_concat = Vec::with_capacity(0); loop { let br = self.stream.read(&mut buf).await?; if br == 0 { return Err(crate::Error::UnparseableReply); } let mut iter = if buf_concat.is_empty() { buf[..br].iter() } else if br + buf_concat.len() < MAX_RESPONSE_LENGTH { buf_concat.extend_from_slice(&buf[..br]); buf_concat.iter() } else { return Err(crate::Error::UnparseableReply); }; match EhloResponse::parse(&mut iter) { Ok(reply) => return Ok(reply), Err(err) => match err { smtp_proto::Error::NeedsMoreData { .. } => { if buf_concat.is_empty() { buf_concat = buf[..br].to_vec(); } } smtp_proto::Error::InvalidResponse { code } => { match ResponseReceiver::from_code(code).parse(&mut iter) { Ok(response) => { return Err(crate::Error::UnexpectedReply(response)); } Err(smtp_proto::Error::NeedsMoreData { .. }) => { if buf_concat.is_empty() { buf_concat = buf[..br].to_vec(); } } Err(_) => return Err(crate::Error::UnparseableReply), } } _ => { return Err(crate::Error::UnparseableReply); } }, } } } } mail-send-0.5.0/src/smtp/envelope.rs000066400000000000000000000051561474544475200173510ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use crate::SmtpClient; use super::{message::Parameters, AssertReply}; impl SmtpClient { /// Sends a MAIL FROM command to the server. pub async fn mail_from(&mut self, addr: &str, params: &Parameters<'_>) -> crate::Result<()> { self.cmd(format!("MAIL FROM:<{addr}>{params}\r\n").as_bytes()) .await? .assert_positive_completion() } /// Sends a RCPT TO command to the server. pub async fn rcpt_to(&mut self, addr: &str, params: &Parameters<'_>) -> crate::Result<()> { self.cmd(format!("RCPT TO:<{addr}>{params}\r\n").as_bytes()) .await? .assert_positive_completion() } /// Sends a DATA command to the server. pub async fn data(&mut self, message: impl AsRef<[u8]>) -> crate::Result<()> { self.cmd(b"DATA\r\n").await?.assert_code(354)?; tokio::time::timeout(self.timeout, async { // Write message self.write_message(message.as_ref()).await?; self.read().await }) .await .map_err(|_| crate::Error::Timeout)?? .assert_positive_completion() } /// Sends a BDAT command to the server. pub async fn bdat(&mut self, message: impl AsRef<[u8]>) -> crate::Result<()> { let message = message.as_ref(); tokio::time::timeout(self.timeout, async { self.stream .write_all(format!("BDAT {} LAST\r\n", message.len()).as_bytes()) .await?; self.stream.write_all(message).await?; self.stream.flush().await?; self.read().await }) .await .map_err(|_| crate::Error::Timeout)?? .assert_positive_completion() } /// Sends a RSET command to the server. pub async fn rset(&mut self) -> crate::Result<()> { self.cmd(b"RSET\r\n").await?.assert_positive_completion() } /// Sends a NOOP command to the server. pub async fn noop(&mut self) -> crate::Result<()> { self.cmd(b"NOOP\r\n").await?.assert_positive_completion() } /// Sends a QUIT command to the server. pub async fn quit(mut self) -> crate::Result<()> { self.cmd(b"QUIT\r\n").await?.assert_positive_completion() } } mail-send-0.5.0/src/smtp/message.rs000066400000000000000000000311201474544475200171460ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use std::{ borrow::Cow, fmt::{Debug, Display}, }; #[cfg(feature = "builder")] use mail_builder::{ headers::{address, HeaderType}, MessageBuilder, }; #[cfg(feature = "parser")] use mail_parser::{HeaderName, HeaderValue}; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use crate::SmtpClient; #[derive(Debug, Default, Clone)] pub struct Message<'x> { pub mail_from: Address<'x>, pub rcpt_to: Vec>, pub body: Cow<'x, [u8]>, } #[derive(Debug, Default, Clone)] pub struct Address<'x> { pub email: Cow<'x, str>, pub parameters: Parameters<'x>, } #[derive(Debug, Default, Clone)] pub struct Parameters<'x> { params: Vec>, } #[derive(Debug, Default, Clone)] pub struct Parameter<'x> { key: Cow<'x, str>, value: Option>, } impl SmtpClient { /// Sends a message to the server. pub async fn send<'x>(&mut self, message: impl IntoMessage<'x>) -> crate::Result<()> { // Send mail-from let message = message.into_message()?; self.mail_from( message.mail_from.email.as_ref(), &message.mail_from.parameters, ) .await?; // Send rcpt-to for rcpt in &message.rcpt_to { self.rcpt_to(rcpt.email.as_ref(), &rcpt.parameters).await?; } // Send message self.data(message.body.as_ref()).await } /// Sends a message to the server. #[cfg(feature = "dkim")] pub async fn send_signed<'x, V: mail_auth::common::crypto::SigningKey>( &mut self, message: impl IntoMessage<'x>, signer: &mail_auth::dkim::DkimSigner, ) -> crate::Result<()> { // Send mail-from use mail_auth::common::headers::HeaderWriter; let message = message.into_message()?; self.mail_from( message.mail_from.email.as_ref(), &message.mail_from.parameters, ) .await?; // Send rcpt-to for rcpt in &message.rcpt_to { self.rcpt_to(rcpt.email.as_ref(), &rcpt.parameters).await?; } // Sign message let signature = signer .sign(message.body.as_ref()) .map_err(|_| crate::Error::MissingCredentials)?; let mut signed_message = Vec::with_capacity(message.body.len() + 64); signature.write_header(&mut signed_message); signed_message.extend_from_slice(message.body.as_ref()); // Send message self.data(&signed_message).await } pub async fn write_message(&mut self, message: &[u8]) -> tokio::io::Result<()> { // Transparency procedure let mut is_cr_or_lf = false; // As per RFC 5322bis, section 2.3: // CR and LF MUST only occur together as CRLF; they MUST NOT appear // independently in the body. // For this reason, we apply the transparency procedure when there is // a CR or LF followed by a dot. let mut last_pos = 0; for (pos, byte) in message.iter().enumerate() { if *byte == b'.' && is_cr_or_lf { if let Some(bytes) = message.get(last_pos..pos) { self.stream.write_all(bytes).await?; self.stream.write_all(b".").await?; last_pos = pos; } is_cr_or_lf = false; } else { is_cr_or_lf = *byte == b'\n' || *byte == b'\r'; } } if let Some(bytes) = message.get(last_pos..) { self.stream.write_all(bytes).await?; } self.stream.write_all("\r\n.\r\n".as_bytes()).await?; self.stream.flush().await } } impl<'x> Message<'x> { /// Create a new message pub fn new(from: T, to: U, body: V) -> Self where T: Into>, U: IntoIterator, V: Into>, { Message { mail_from: from.into(), rcpt_to: to.into_iter().map(Into::into).collect(), body: body.into(), } } /// Create a new empty message. pub fn empty() -> Self { Message { mail_from: Address::default(), rcpt_to: Vec::new(), body: Default::default(), } } /// Set the sender of the message. pub fn from(mut self, address: impl Into>) -> Self { self.mail_from = address.into(); self } /// Add a message recipient. pub fn to(mut self, address: impl Into>) -> Self { self.rcpt_to.push(address.into()); self } /// Set the message body. pub fn body(mut self, body: impl Into>) -> Self { self.body = body.into(); self } } impl<'x> From<&'x str> for Address<'x> { fn from(email: &'x str) -> Self { Address { email: email.into(), parameters: Parameters::default(), } } } impl From for Address<'_> { fn from(email: String) -> Self { Address { email: email.into(), parameters: Parameters::default(), } } } impl<'x> Address<'x> { pub fn new(email: impl Into>, parameters: Parameters<'x>) -> Self { Address { email: email.into(), parameters, } } } impl<'x> Parameters<'x> { pub fn new() -> Self { Self { params: Vec::new() } } pub fn add(&mut self, param: impl Into>) -> &mut Self { self.params.push(param.into()); self } } impl<'x> From<&'x str> for Parameter<'x> { fn from(value: &'x str) -> Self { Parameter { key: value.into(), value: None, } } } impl<'x> From<(&'x str, &'x str)> for Parameter<'x> { fn from(value: (&'x str, &'x str)) -> Self { Parameter { key: value.0.into(), value: Some(value.1.into()), } } } impl From<(String, String)> for Parameter<'_> { fn from(value: (String, String)) -> Self { Parameter { key: value.0.into(), value: Some(value.1.into()), } } } impl From for Parameter<'_> { fn from(value: String) -> Self { Parameter { key: value.into(), value: None, } } } impl Display for Parameters<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if !self.params.is_empty() { for param in &self.params { f.write_str(" ")?; Display::fmt(¶m, f)?; } } Ok(()) } } impl Display for Parameter<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(value) = &self.value { write!(f, "{}={}", self.key, value) } else { f.write_str(&self.key) } } } pub trait IntoMessage<'x> { fn into_message(self) -> crate::Result>; } impl<'x> IntoMessage<'x> for Message<'x> { fn into_message(self) -> crate::Result> { Ok(self) } } #[cfg(feature = "builder")] impl<'x> IntoMessage<'x> for MessageBuilder<'_> { fn into_message(self) -> crate::Result> { let mut mail_from = None; let mut rcpt_to = std::collections::HashSet::new(); for (key, value) in self.headers.iter() { if key.eq_ignore_ascii_case("from") { if let HeaderType::Address(address::Address::Address(addr)) = value { let email = addr.email.trim(); if !email.is_empty() { mail_from = email.to_string().into(); } } } else if key.eq_ignore_ascii_case("to") || key.eq_ignore_ascii_case("cc") || key.eq_ignore_ascii_case("bcc") { if let HeaderType::Address(addr) = value { match addr { address::Address::Address(addr) => { let email = addr.email.trim(); if !email.is_empty() { rcpt_to.insert(email.to_string()); } } address::Address::Group(group) => { for addr in &group.addresses { if let address::Address::Address(addr) = addr { let email = addr.email.trim(); if !email.is_empty() { rcpt_to.insert(email.to_string()); } } } } address::Address::List(list) => { for addr in list { if let address::Address::Address(addr) = addr { let email = addr.email.trim(); if !email.is_empty() { rcpt_to.insert(email.to_string()); } } } } } } } } if rcpt_to.is_empty() { return Err(crate::Error::MissingRcptTo); } Ok(Message { mail_from: mail_from.ok_or(crate::Error::MissingMailFrom)?.into(), rcpt_to: rcpt_to .into_iter() .map(|email| Address { email: email.into(), parameters: Parameters::default(), }) .collect(), body: self.write_to_vec()?.into(), }) } } #[cfg(feature = "parser")] impl<'x> IntoMessage<'x> for mail_parser::Message<'x> { fn into_message(self) -> crate::Result> { let mut mail_from = None; let mut rcpt_to = std::collections::HashSet::new(); let find_address = |addr: &mail_parser::Addr| -> Option { addr.address .as_ref() .filter(|address| !address.trim().is_empty()) .map(|address| address.trim().to_string()) }; for header in self.headers() { match &header.name { HeaderName::From => match header.value() { HeaderValue::Address(mail_parser::Address::List(addrs)) => { if let Some(email) = addrs.iter().find_map(find_address) { mail_from = email.to_string().into(); } } HeaderValue::Address(mail_parser::Address::Group(groups)) => { if let Some(grps) = groups.first() { if let Some(email) = grps.addresses.iter().find_map(find_address) { mail_from = email.to_string().into(); } } } _ => (), }, HeaderName::To | HeaderName::Cc | HeaderName::Bcc => match header.value() { HeaderValue::Address(mail_parser::Address::List(addrs)) => { rcpt_to.extend(addrs.iter().filter_map(find_address)); } HeaderValue::Address(mail_parser::Address::Group(grps)) => { rcpt_to.extend( grps.iter() .flat_map(|grp| grp.addresses.iter()) .filter_map(find_address), ); } _ => (), }, _ => (), }; } if rcpt_to.is_empty() { return Err(crate::Error::MissingRcptTo); } Ok(Message { mail_from: mail_from.ok_or(crate::Error::MissingMailFrom)?.into(), rcpt_to: rcpt_to .into_iter() .map(|email| Address { email: email.into(), parameters: Parameters::default(), }) .collect(), body: self.raw_message, }) } } mail-send-0.5.0/src/smtp/mod.rs000066400000000000000000000036761474544475200163200ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use smtp_proto::{Response, Severity}; pub mod auth; pub mod builder; pub mod client; pub mod ehlo; pub mod envelope; pub mod message; pub mod tls; impl From for crate::Error { fn from(err: auth::Error) -> Self { crate::Error::Auth(err) } } pub trait AssertReply: Sized { fn is_positive_completion(&self) -> bool; fn assert_positive_completion(self) -> crate::Result<()>; fn assert_severity(self, severity: Severity) -> crate::Result<()>; fn assert_code(self, code: u16) -> crate::Result<()>; } impl AssertReply for Response { /// Returns `true` if the reply is a positive completion. #[inline(always)] fn is_positive_completion(&self) -> bool { (200..=299).contains(&self.code) } /// Returns Ok if the reply has the specified severity. #[inline(always)] fn assert_severity(self, severity: Severity) -> crate::Result<()> { if self.severity() == severity { Ok(()) } else { Err(crate::Error::UnexpectedReply(self)) } } /// Returns Ok if the reply returned a 2xx code. #[inline(always)] fn assert_positive_completion(self) -> crate::Result<()> { if (200..=299).contains(&self.code) { Ok(()) } else { Err(crate::Error::UnexpectedReply(self)) } } /// Returns Ok if the reply has the specified status code. #[inline(always)] fn assert_code(self, code: u16) -> crate::Result<()> { if self.code() == code { Ok(()) } else { Err(crate::Error::UnexpectedReply(self)) } } } mail-send-0.5.0/src/smtp/tls.rs000066400000000000000000000120221474544475200163240ustar00rootroot00000000000000/* * Copyright Stalwart Labs Ltd. * * Licensed under the Apache License, Version 2.0 or the MIT license * , at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use std::{convert::TryFrom, io, sync::Arc}; use rustls::{ client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, ClientConfig, ClientConnection, RootCertStore, SignatureScheme, }; use rustls_pki_types::{ServerName, TrustAnchor}; use tokio::net::TcpStream; use tokio_rustls::{client::TlsStream, TlsConnector}; use crate::{Error, SmtpClient}; use super::AssertReply; impl SmtpClient { /// Upgrade the connection to TLS. pub async fn start_tls( mut self, tls_connector: &TlsConnector, hostname: &str, ) -> crate::Result>> { // Send STARTTLS command self.cmd(b"STARTTLS\r\n") .await? .assert_positive_completion()?; self.into_tls(tls_connector, hostname).await } pub async fn into_tls( self, tls_connector: &TlsConnector, hostname: &str, ) -> crate::Result>> { tokio::time::timeout(self.timeout, async { Ok(SmtpClient { stream: tls_connector .connect( ServerName::try_from(hostname) .map_err(|_| crate::Error::InvalidTLSName)? .to_owned(), self.stream, ) .await .map_err(|err| { let kind = err.kind(); if let Some(inner) = err.into_inner() { match inner.downcast::() { Ok(error) => Error::Tls(error), Err(error) => Error::Io(io::Error::new(kind, error)), } } else { Error::Io(io::Error::new(kind, "Unspecified")) } })?, timeout: self.timeout, }) }) .await .map_err(|_| crate::Error::Timeout)? } } impl SmtpClient> { pub fn tls_connection(&self) -> &ClientConnection { self.stream.get_ref().1 } } pub fn build_tls_connector(allow_invalid_certs: bool) -> TlsConnector { let config = if !allow_invalid_certs { let mut root_cert_store = RootCertStore::empty(); root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| TrustAnchor { subject: ta.subject.clone(), subject_public_key_info: ta.subject_public_key_info.clone(), name_constraints: ta.name_constraints.clone(), })); ClientConfig::builder() .with_root_certificates(root_cert_store) .with_no_client_auth() } else { ClientConfig::builder() .dangerous() .with_custom_certificate_verifier(Arc::new(DummyVerifier {})) .with_no_client_auth() }; TlsConnector::from(Arc::new(config)) } #[doc(hidden)] #[derive(Debug)] struct DummyVerifier; impl ServerCertVerifier for DummyVerifier { fn verify_server_cert( &self, _end_entity: &rustls_pki_types::CertificateDer<'_>, _intermediates: &[rustls_pki_types::CertificateDer<'_>], _server_name: &rustls_pki_types::ServerName<'_>, _ocsp_response: &[u8], _now: rustls_pki_types::UnixTime, ) -> Result { Ok(ServerCertVerified::assertion()) } fn verify_tls12_signature( &self, _message: &[u8], _cert: &rustls_pki_types::CertificateDer<'_>, _dss: &rustls::DigitallySignedStruct, ) -> Result { Ok(HandshakeSignatureValid::assertion()) } fn verify_tls13_signature( &self, _message: &[u8], _cert: &rustls_pki_types::CertificateDer<'_>, _dss: &rustls::DigitallySignedStruct, ) -> Result { Ok(HandshakeSignatureValid::assertion()) } fn supported_verify_schemes(&self) -> Vec { vec![ SignatureScheme::RSA_PKCS1_SHA1, SignatureScheme::ECDSA_SHA1_Legacy, SignatureScheme::RSA_PKCS1_SHA256, SignatureScheme::ECDSA_NISTP256_SHA256, SignatureScheme::RSA_PKCS1_SHA384, SignatureScheme::ECDSA_NISTP384_SHA384, SignatureScheme::RSA_PKCS1_SHA512, SignatureScheme::ECDSA_NISTP521_SHA512, SignatureScheme::RSA_PSS_SHA256, SignatureScheme::RSA_PSS_SHA384, SignatureScheme::RSA_PSS_SHA512, SignatureScheme::ED25519, SignatureScheme::ED448, ] } }