Implement creating SmtpTransport using STARTTLS

This commit is contained in:
Manuel Pelloni
2020-08-18 23:27:07 +02:00
committed by Alexis Mousset
parent 60e3a0b7cb
commit f865fc1bce
4 changed files with 45 additions and 2 deletions

View File

@@ -71,5 +71,9 @@ name = "smtp"
required-features = ["smtp-transport"]
[[example]]
name = "smtp_gmail"
name = "smtp_tls"
required-features = ["smtp-transport", "native-tls"]
[[example]]
name = "smtp_starttls"
required-features = ["smtp-transport", "native-tls"]

26
examples/smtp_starttls.rs Normal file
View File

@@ -0,0 +1,26 @@
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};
fn main() {
let email = Message::builder()
.from("NoBody <nobody@domain.tld>".parse().unwrap())
.reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
.to("Hei <hei@domain.tld>".parse().unwrap())
.subject("Happy new year")
.body("Be happy!")
.unwrap();
let creds = Credentials::new("smtp_username".to_string(), "smtp_password".to_string());
// Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay("smtp.gmail.com")
.unwrap()
.credentials(creds)
.build();
// Send the email
match mailer.send(&email) {
Ok(_) => println!("Email sent successfully!"),
Err(e) => panic!("Could not send email: {:?}", e),
}
}

View File

@@ -5,7 +5,7 @@ use r2d2::{Builder, Pool};
use super::{ClientId, Credentials, Error, Mechanism, Response, SmtpConnection, SmtpInfo};
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
use super::{Tls, TlsParameters, SUBMISSIONS_PORT};
use super::{Tls, TlsParameters, SUBMISSIONS_PORT, SUBMISSION_PORT};
use crate::{Envelope, Transport};
#[allow(missing_debug_implementations)]
@@ -50,6 +50,19 @@ impl SmtpTransport {
.tls(Tls::Wrapper(tls_parameters)))
}
/// Simple and secure transport, should be used when the server doesn't support wrapped TLS connections.
/// Creates an encrypted transport over submissions port, by first connecting using an unencrypted
/// connection and then upgrading it with STARTTLS, using the provided domain to validate TLS certificates.
/// If the connection can't be upgraded it will fail connecting altogether.
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
pub fn starttls_relay(relay: &str) -> Result<SmtpTransportBuilder, Error> {
let tls_parameters = TlsParameters::new(relay.into())?;
Ok(Self::builder_dangerous(relay)
.port(SUBMISSION_PORT)
.tls(Tls::Required(tls_parameters)))
}
/// Creates a new local SMTP client to port 25
///
/// Shortcut for local unencrypted relay (typical local email daemon that will handle relaying)