Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af20cfa8ff | ||
|
|
7a9f9111a5 | ||
|
|
89c0be219d | ||
|
|
6ee7fdb3d1 | ||
|
|
b7ac3a897f | ||
|
|
c436716277 | ||
|
|
eabdb960b0 | ||
|
|
59ba9e84dc | ||
|
|
e569c030bc | ||
|
|
72aea756fa | ||
|
|
655ae6d2ff | ||
|
|
150536d242 | ||
|
|
7d707fab25 | ||
|
|
4ec34987f8 | ||
|
|
7f3680f125 | ||
|
|
67566c2152 | ||
|
|
d863a7677e | ||
|
|
c1fe40479b | ||
|
|
8d03545062 | ||
|
|
489a6e892e | ||
|
|
b3fe1e0f65 | ||
|
|
3612ffca7a | ||
|
|
7940ad6c15 | ||
|
|
5ffb169bc9 | ||
|
|
ea0bb256cd | ||
|
|
9f177047f8 | ||
|
|
48eb859804 | ||
|
|
8d9877233d | ||
|
|
09f61a9fc9 | ||
|
|
40e749a04a |
33
.travis.yml
33
.travis.yml
@@ -1,12 +1,9 @@
|
||||
language: rust
|
||||
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
sudo: false
|
||||
|
||||
cache:
|
||||
apt: true
|
||||
pip: true
|
||||
@@ -15,9 +12,9 @@ cache:
|
||||
- target/debug/build
|
||||
- target/release/deps
|
||||
- target/release/build
|
||||
|
||||
install: pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH
|
||||
|
||||
install:
|
||||
- pip install 'travis-cargo<0.2' --user
|
||||
- export PATH=$HOME/.local/bin:$PATH
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
@@ -25,20 +22,16 @@ addons:
|
||||
- libcurl4-openssl-dev
|
||||
- libelf-dev
|
||||
- libdw-dev
|
||||
|
||||
before_script:
|
||||
- smtp-sink 2525 1000&
|
||||
|
||||
- smtp-sink 2525 1000&
|
||||
script:
|
||||
- travis-cargo build
|
||||
- travis-cargo test
|
||||
- travis-cargo doc
|
||||
|
||||
- travis-cargo build
|
||||
- travis-cargo test
|
||||
- travis-cargo doc
|
||||
after_success:
|
||||
- travis-cargo --only nightly bench
|
||||
- travis-cargo --only stable doc-upload
|
||||
- travis-cargo --only stable coveralls --no-sudo
|
||||
|
||||
- travis-cargo --only nightly bench
|
||||
- travis-cargo --only stable coveralls --no-sudo
|
||||
- travis-cargo --only stable doc-upload
|
||||
env:
|
||||
global:
|
||||
secure: "MaZ3TzuaAHuxmxQkfJdqRfkh7/ieScJRk0T/2yjysZhDMTYyRmp5wh/zkfW1ADuG0uc4Pqsxrsh1J9SVO7O0U5NJA8NKZi/pgiL+FHh0g4YtlHxy2xmFNB5am3Kyc+E7B4XylwTbA9S8ublVM0nvX7yX/a5fbwEUInVk2bA8fpc="
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
|
||||
name = "lettre"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
description = "Email client"
|
||||
readme = "README.md"
|
||||
documentation = "http://lettre.github.io/lettre/"
|
||||
@@ -18,7 +18,7 @@ rustc-serialize = "0.3"
|
||||
rust-crypto = "0.2"
|
||||
bufstream = "0.1"
|
||||
email = "0.0"
|
||||
openssl = "0.6"
|
||||
openssl = "0.7"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.3"
|
||||
|
||||
@@ -5,13 +5,11 @@ extern crate test;
|
||||
|
||||
use lettre::transport::smtp::SmtpTransportBuilder;
|
||||
use lettre::transport::EmailTransport;
|
||||
use lettre::mailer::Mailer;
|
||||
use lettre::email::EmailBuilder;
|
||||
|
||||
#[bench]
|
||||
fn bench_simple_send(b: &mut test::Bencher) {
|
||||
let sender = SmtpTransportBuilder::new("127.0.0.1:2525").unwrap().build();
|
||||
let mut mailer = Mailer::new(sender);
|
||||
let mut sender = SmtpTransportBuilder::new("127.0.0.1:2525").unwrap().build();
|
||||
b.iter(|| {
|
||||
let email = EmailBuilder::new()
|
||||
.to("root@localhost")
|
||||
@@ -20,18 +18,17 @@ fn bench_simple_send(b: &mut test::Bencher) {
|
||||
.subject("Hello")
|
||||
.build()
|
||||
.unwrap();
|
||||
let result = mailer.send(email);
|
||||
let result = sender.send(email);
|
||||
assert!(result.is_ok());
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_reuse_send(b: &mut test::Bencher) {
|
||||
let sender = SmtpTransportBuilder::new("127.0.0.1:2525")
|
||||
let mut sender = SmtpTransportBuilder::new("127.0.0.1:2525")
|
||||
.unwrap()
|
||||
.connection_reuse(true)
|
||||
.build();
|
||||
let mut mailer = Mailer::new(sender);
|
||||
b.iter(|| {
|
||||
let email = EmailBuilder::new()
|
||||
.to("root@localhost")
|
||||
@@ -40,8 +37,8 @@ fn bench_reuse_send(b: &mut test::Bencher) {
|
||||
.subject("Hello")
|
||||
.build()
|
||||
.unwrap();
|
||||
let result = mailer.send(email);
|
||||
let result = sender.send(email);
|
||||
assert!(result.is_ok());
|
||||
});
|
||||
mailer.close()
|
||||
sender.close()
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
extern crate lettre;
|
||||
|
||||
use lettre::transport::file::FileEmailTransport;
|
||||
use lettre::transport::EmailTransport;
|
||||
use lettre::email::EmailBuilder;
|
||||
|
||||
|
||||
fn main() {
|
||||
let mut sender = FileEmailTransport::new("/tmp/");
|
||||
let email = EmailBuilder::new()
|
||||
.to("root@localhost")
|
||||
.from("user@localhost")
|
||||
.body("Hello World!")
|
||||
.subject("Hello")
|
||||
.build()
|
||||
.unwrap();
|
||||
let result = sender.send(email);
|
||||
println!("{:?}", result);
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@@ -0,0 +1 @@
|
||||
reorder_imports = true
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Simple email (very incomplete)
|
||||
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use email_format::{MimeMessage, Header, Mailbox};
|
||||
use time::{now, Tm};
|
||||
use email_format::{Header, Mailbox, MimeMessage};
|
||||
use time::{Tm, now};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Converts an adress or an address with an alias to a `Address`
|
||||
@@ -219,10 +219,10 @@ pub struct SimpleSendableEmail {
|
||||
|
||||
impl SimpleSendableEmail {
|
||||
/// Returns a new email
|
||||
pub fn new(from_address: &str, to_address: &str, message: &str) -> SimpleSendableEmail {
|
||||
pub fn new(from_address: &str, to_address: Vec<String>, message: &str) -> SimpleSendableEmail {
|
||||
SimpleSendableEmail {
|
||||
from: from_address.to_string(),
|
||||
to: vec![to_address.to_string()],
|
||||
to: to_address,
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
@@ -269,9 +269,9 @@ mod test {
|
||||
use time::now;
|
||||
|
||||
use uuid::Uuid;
|
||||
use email_format::{MimeMessage, Header};
|
||||
use email_format::{Header, MimeMessage};
|
||||
|
||||
use super::{SendableEmail, EmailBuilder, Email};
|
||||
use super::{Email, EmailBuilder, SendableEmail};
|
||||
|
||||
#[test]
|
||||
fn test_email_display() {
|
||||
|
||||
126
src/lib.rs
126
src/lib.rs
@@ -1,6 +1,16 @@
|
||||
//! # Rust email client
|
||||
//! Lettre is a mailer written in Rust. It provides a simple email builder and several transports.
|
||||
//!
|
||||
//! This client should tend to follow [RFC
|
||||
//! ## Architecture
|
||||
//!
|
||||
//! This mailer is divided into:
|
||||
//!
|
||||
//! * An `email` part: builds the email message
|
||||
//! * A `transport` part: contains the available transports for your emails. To be sendable, the
|
||||
//! emails have to implement `SendableEmail`.
|
||||
//!
|
||||
//! ## SMTP transport
|
||||
//!
|
||||
//! This SMTP follows [RFC
|
||||
//! 5321](https://tools.ietf.org/html/rfc5321), but is still
|
||||
//! a work in progress. It is designed to efficiently send emails from an
|
||||
//! application to a
|
||||
@@ -12,20 +22,10 @@
|
||||
//!
|
||||
//! * 8BITMIME ([RFC 6152](https://tools.ietf.org/html/rfc6152))
|
||||
//! * AUTH ([RFC 4954](http://tools.ietf.org/html/rfc4954)) with PLAIN and
|
||||
//! CRAM-MD5 mecanisms
|
||||
//! CRAM-MD5 mechanisms
|
||||
//! * STARTTLS ([RFC 2487](http://tools.ietf.org/html/rfc2487))
|
||||
//! * SMTPUTF8 ([RFC 6531](http://tools.ietf.org/html/rfc6531))
|
||||
//!
|
||||
//! ## Architecture
|
||||
//!
|
||||
//! This client is divided into three main parts:
|
||||
//!
|
||||
//! * transport: a low level SMTP client providing all SMTP commands
|
||||
//! * mailer: a high level SMTP client providing an easy method to send emails
|
||||
//! * email: generates the email to be sent with the sender
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! ### Simple example
|
||||
//!
|
||||
//! This is the most basic example of usage:
|
||||
@@ -60,7 +60,7 @@
|
||||
//! use lettre::email::EmailBuilder;
|
||||
//! use lettre::transport::smtp::{SecurityLevel, SmtpTransport,
|
||||
//! SmtpTransportBuilder};
|
||||
//! use lettre::transport::smtp::authentication::Mecanism;
|
||||
//! use lettre::transport::smtp::authentication::Mechanism;
|
||||
//! use lettre::transport::smtp::SUBMISSION_PORT;
|
||||
//! use lettre::transport::EmailTransport;
|
||||
//!
|
||||
@@ -89,8 +89,8 @@
|
||||
//! .security_level(SecurityLevel::AlwaysEncrypt)
|
||||
//! // Enable SMTPUTF8 is the server supports it
|
||||
//! .smtp_utf8(true)
|
||||
//! // Configure accepted authetication mecanisms
|
||||
//! .authentication_mecanisms(vec![Mecanism::CramMd5])
|
||||
//! // Configure accepted authetication mechanisms
|
||||
//! .authentication_mechanisms(vec![Mechanism::CramMd5])
|
||||
//! // Enable connection reuse
|
||||
//! .connection_reuse(true).build();
|
||||
//!
|
||||
@@ -105,28 +105,6 @@
|
||||
//! mailer.close();
|
||||
//! ```
|
||||
//!
|
||||
//! ### Using the client directly
|
||||
//!
|
||||
//! If you just want to send an email without using `Email` to provide headers:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use lettre::email::SimpleSendableEmail;
|
||||
//! use lettre::transport::smtp::{SmtpTransport, SmtpTransportBuilder};
|
||||
//! use lettre::transport::EmailTransport;
|
||||
//!
|
||||
//! // Create a minimal email
|
||||
//! let email = SimpleSendableEmail::new(
|
||||
//! "test@example.com",
|
||||
//! "test@example.org",
|
||||
//! "Hello world !"
|
||||
//! );
|
||||
//!
|
||||
//! let mut mailer =
|
||||
//! SmtpTransportBuilder::localhost().unwrap().build();
|
||||
//! let result = mailer.send(email);
|
||||
//! assert!(result.is_ok());
|
||||
//! ```
|
||||
//!
|
||||
//! ### Lower level
|
||||
//!
|
||||
//! You can also send commands, here is a simple email transaction without
|
||||
@@ -138,7 +116,7 @@
|
||||
//! use lettre::transport::smtp::client::net::NetworkStream;
|
||||
//!
|
||||
//! let mut email_client: Client<NetworkStream> = Client::new();
|
||||
//! let _ = email_client.connect(&("localhost", SMTP_PORT));
|
||||
//! let _ = email_client.connect(&("localhost", SMTP_PORT), None);
|
||||
//! let _ = email_client.ehlo("my_hostname");
|
||||
//! let _ = email_client.mail("user@example.com", None);
|
||||
//! let _ = email_client.rcpt("user@example.org");
|
||||
@@ -146,8 +124,76 @@
|
||||
//! let _ = email_client.message("Test email");
|
||||
//! let _ = email_client.quit();
|
||||
//! ```
|
||||
//!
|
||||
//! ## Stub transport
|
||||
//!
|
||||
//! The stub transport only logs message envelope and drops the content. It can be useful for
|
||||
//! testing purposes.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use lettre::transport::stub::StubEmailTransport;
|
||||
//! use lettre::transport::EmailTransport;
|
||||
//! use lettre::email::EmailBuilder;
|
||||
//!
|
||||
//! let mut sender = StubEmailTransport;
|
||||
//! let email = EmailBuilder::new()
|
||||
//! .to("root@localhost")
|
||||
//! .from("user@localhost")
|
||||
//! .body("Hello World!")
|
||||
//! .subject("Hello")
|
||||
//! .build()
|
||||
//! .unwrap();
|
||||
//! let result = sender.send(email);
|
||||
//! assert!(result.is_ok());
|
||||
//! ```
|
||||
//!
|
||||
//! Will log the line:
|
||||
//!
|
||||
//! ```text
|
||||
//! b7c211bc-9811-45ce-8cd9-68eab575d695: from=<user@localhost> to=<root@localhost>
|
||||
//! ```
|
||||
//!
|
||||
//! ## File transport
|
||||
//!
|
||||
//! The file transport writes the emails to the given directory. The name of the file will be
|
||||
//! `message_id.txt`.
|
||||
//! It can be useful for testing purposes.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use std::env::temp_dir;
|
||||
//!
|
||||
//! use lettre::transport::file::FileEmailTransport;
|
||||
//! use lettre::transport::EmailTransport;
|
||||
//! use lettre::email::{EmailBuilder, SendableEmail};
|
||||
//!
|
||||
//! // Write to the local temp directory
|
||||
//! let mut sender = FileEmailTransport::new(temp_dir());
|
||||
//! let email = EmailBuilder::new()
|
||||
//! .to("root@localhost")
|
||||
//! .from("user@localhost")
|
||||
//! .body("Hello World!")
|
||||
//! .subject("Hello")
|
||||
//! .build()
|
||||
//! .unwrap();
|
||||
//!
|
||||
//! let result = sender.send(email);
|
||||
//! assert!(result.is_ok());
|
||||
//! ```
|
||||
//! Example result in `/tmp/b7c211bc-9811-45ce-8cd9-68eab575d695.txt`:
|
||||
//!
|
||||
//! ```text
|
||||
//! b7c211bc-9811-45ce-8cd9-68eab575d695: from=<user@localhost> to=<root@localhost>
|
||||
//! To: <root@localhost>
|
||||
//! From: <user@localhost>
|
||||
//! Subject: Hello
|
||||
//! Date: Sat, 31 Oct 2015 13:42:19 +0100
|
||||
//! Message-ID: <b7c211bc-9811-45ce-8cd9-68eab575d695.lettre@localhost>
|
||||
//!
|
||||
//! Hello World!
|
||||
//! ```
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#![deny(missing_docs, unsafe_code, unstable_features)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use std::error::Error as StdError;
|
||||
use std::io;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use transport::smtp::response::{Severity, Response};
|
||||
use transport::smtp::response::{Response, Severity};
|
||||
use rustc_serialize::base64::FromBase64Error;
|
||||
use self::Error::*;
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
//! TODO
|
||||
//! This transport creates a file for each email, containing the enveloppe information and the email
|
||||
//! itself.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::io::prelude::*;
|
||||
use std::fs::File;
|
||||
|
||||
use transport::EmailTransport;
|
||||
use transport::error::EmailResult;
|
||||
use transport::smtp::response::Response;
|
||||
use transport::EmailTransport;
|
||||
use transport::smtp::response::{Code, Category, Severity};
|
||||
use transport::smtp::response::{Category, Code, Severity};
|
||||
use email::SendableEmail;
|
||||
|
||||
|
||||
/// TODO
|
||||
/// Writes the content and the enveloppe information to a file
|
||||
pub struct FileEmailTransport {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Provides authentication mecanisms
|
||||
//! Provides authentication mechanisms
|
||||
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use rustc_serialize::base64::{self, ToBase64, FromBase64};
|
||||
use rustc_serialize::base64::{self, FromBase64, ToBase64};
|
||||
use rustc_serialize::hex::ToHex;
|
||||
use crypto::hmac::Hmac;
|
||||
use crypto::md5::Md5;
|
||||
@@ -12,34 +12,34 @@ use crypto::mac::Mac;
|
||||
use transport::smtp::NUL;
|
||||
use transport::error::Error;
|
||||
|
||||
/// Represents authentication mecanisms
|
||||
/// Represents authentication mechanisms
|
||||
#[derive(PartialEq,Eq,Copy,Clone,Hash,Debug)]
|
||||
pub enum Mecanism {
|
||||
/// PLAIN authentication mecanism
|
||||
pub enum Mechanism {
|
||||
/// PLAIN authentication mechanism
|
||||
/// RFC 4616: https://tools.ietf.org/html/rfc4616
|
||||
Plain,
|
||||
/// CRAM-MD5 authentication mecanism
|
||||
/// CRAM-MD5 authentication mechanism
|
||||
/// RFC 2195: https://tools.ietf.org/html/rfc2195
|
||||
CramMd5,
|
||||
}
|
||||
|
||||
impl Display for Mecanism {
|
||||
impl Display for Mechanism {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f,
|
||||
"{}",
|
||||
match *self {
|
||||
Mecanism::Plain => "PLAIN",
|
||||
Mecanism::CramMd5 => "CRAM-MD5",
|
||||
Mechanism::Plain => "PLAIN",
|
||||
Mechanism::CramMd5 => "CRAM-MD5",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Mecanism {
|
||||
/// Does the mecanism supports initial response
|
||||
impl Mechanism {
|
||||
/// Does the mechanism supports initial response
|
||||
pub fn supports_initial_response(&self) -> bool {
|
||||
match *self {
|
||||
Mecanism::Plain => true,
|
||||
Mecanism::CramMd5 => false,
|
||||
Mechanism::Plain => true,
|
||||
Mechanism::CramMd5 => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,18 +51,20 @@ impl Mecanism {
|
||||
challenge: Option<&str>)
|
||||
-> Result<String, Error> {
|
||||
match *self {
|
||||
Mecanism::Plain => {
|
||||
Mechanism::Plain => {
|
||||
match challenge {
|
||||
Some(_) => Err(Error::ClientError("This mecanism does not expect a challenge")),
|
||||
Some(_) =>
|
||||
Err(Error::ClientError("This mechanism does not expect a challenge")),
|
||||
None => Ok(format!("{}{}{}{}", NUL, username, NUL, password)
|
||||
.as_bytes()
|
||||
.to_base64(base64::STANDARD)),
|
||||
}
|
||||
}
|
||||
Mecanism::CramMd5 => {
|
||||
Mechanism::CramMd5 => {
|
||||
let encoded_challenge = match challenge {
|
||||
Some(challenge) => challenge,
|
||||
None => return Err(Error::ClientError("This mecanism does expect a challenge")),
|
||||
None =>
|
||||
return Err(Error::ClientError("This mechanism does expect a challenge")),
|
||||
};
|
||||
|
||||
let decoded_challenge = match encoded_challenge.from_base64() {
|
||||
@@ -83,27 +85,28 @@ impl Mecanism {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::Mecanism;
|
||||
use super::Mechanism;
|
||||
|
||||
#[test]
|
||||
fn test_plain() {
|
||||
let mecanism = Mecanism::Plain;
|
||||
let mechanism = Mechanism::Plain;
|
||||
|
||||
assert_eq!(mecanism.response("username", "password", None).unwrap(),
|
||||
assert_eq!(mechanism.response("username", "password", None).unwrap(),
|
||||
"AHVzZXJuYW1lAHBhc3N3b3Jk");
|
||||
assert!(mecanism.response("username", "password", Some("test")).is_err());
|
||||
assert!(mechanism.response("username", "password", Some("test")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cram_md5() {
|
||||
let mecanism = Mecanism::CramMd5;
|
||||
let mechanism = Mechanism::CramMd5;
|
||||
|
||||
assert_eq!(mecanism.response("alice",
|
||||
assert_eq!(mechanism.response("alice",
|
||||
"wonderland",
|
||||
Some("PDE3ODkzLjEzMjA2NzkxMjNAdGVzc2VyYWN0LnN1c2FtLmluPg=="))
|
||||
Some("PDE3ODkzLjEzMjA2NzkxMjNAdGVzc2VyYWN0LnN1c2FtLmluPg=\
|
||||
="))
|
||||
.unwrap(),
|
||||
"YWxpY2UgNjRiMmE0M2MxZjZlZDY4MDZhOTgwOTE0ZTIzZTc1ZjA=");
|
||||
assert!(mecanism.response("alice", "wonderland", Some("tést")).is_err());
|
||||
assert!(mecanism.response("alice", "wonderland", None).is_err());
|
||||
assert!(mechanism.response("alice", "wonderland", Some("tést")).is_err());
|
||||
assert!(mechanism.response("alice", "wonderland", None).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
|
||||
use std::string::String;
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::io::{BufRead, Read, Write};
|
||||
use std::io;
|
||||
use std::io::{BufRead, Read, Write};
|
||||
use std::fmt::Debug;
|
||||
|
||||
use bufstream::BufStream;
|
||||
use openssl::ssl::SslContext;
|
||||
|
||||
use transport::error::{EmailResult, Error};
|
||||
use transport::smtp::response::ResponseParser;
|
||||
use transport::smtp::authentication::Mecanism;
|
||||
use transport::error::{Error, EmailResult};
|
||||
use transport::smtp::authentication::Mechanism;
|
||||
use transport::smtp::client::net::{Connector, NetworkStream};
|
||||
use transport::smtp::{CRLF, MESSAGE_ENDING};
|
||||
|
||||
@@ -88,7 +88,10 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
|
||||
}
|
||||
|
||||
/// Connects to the configured server
|
||||
pub fn connect<A: ToSocketAddrs>(&mut self, addr: &A) -> EmailResult {
|
||||
pub fn connect<A: ToSocketAddrs>(&mut self,
|
||||
addr: &A,
|
||||
ssl_context: Option<&SslContext>)
|
||||
-> EmailResult {
|
||||
// Connect should not be called when the client is already connected
|
||||
if self.stream.is_some() {
|
||||
return_err!("The connection is already established", self);
|
||||
@@ -102,7 +105,7 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
|
||||
};
|
||||
|
||||
// Try to connect
|
||||
self.set_stream(try!(Connector::connect(&server_addr, None)));
|
||||
self.set_stream(try!(Connector::connect(&server_addr, ssl_context)));
|
||||
|
||||
self.get_reply()
|
||||
}
|
||||
@@ -173,13 +176,13 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
|
||||
self.command("RSET")
|
||||
}
|
||||
|
||||
/// Sends an AUTH command with the given mecanism
|
||||
pub fn auth(&mut self, mecanism: Mecanism, username: &str, password: &str) -> EmailResult {
|
||||
/// Sends an AUTH command with the given mechanism
|
||||
pub fn auth(&mut self, mechanism: Mechanism, username: &str, password: &str) -> EmailResult {
|
||||
|
||||
if mecanism.supports_initial_response() {
|
||||
if mechanism.supports_initial_response() {
|
||||
self.command(&format!("AUTH {} {}",
|
||||
mecanism,
|
||||
try!(mecanism.response(username, password, None))))
|
||||
mechanism,
|
||||
try!(mechanism.response(username, password, None))))
|
||||
} else {
|
||||
let encoded_challenge = match try!(self.command("AUTH CRAM-MD5")).first_word() {
|
||||
Some(challenge) => challenge,
|
||||
@@ -188,7 +191,7 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
|
||||
|
||||
debug!("CRAM challenge: {}", encoded_challenge);
|
||||
|
||||
let cram_response = try!(mecanism.response(username,
|
||||
let cram_response = try!(mechanism.response(username,
|
||||
password,
|
||||
Some(&encoded_challenge)));
|
||||
|
||||
@@ -246,7 +249,7 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::{escape_dot, remove_crlf, escape_crlf};
|
||||
use super::{escape_crlf, escape_dot, remove_crlf};
|
||||
|
||||
#[test]
|
||||
fn test_escape_dot() {
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
//! A trait to represent a stream
|
||||
|
||||
use std::io;
|
||||
use std::io::{Read, Write, ErrorKind};
|
||||
use std::net::SocketAddr;
|
||||
use std::net::TcpStream;
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::fmt;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
|
||||
use openssl::ssl::{SslContext, SslStream};
|
||||
|
||||
/// A trait for the concept of opening a stream
|
||||
pub trait Connector {
|
||||
pub trait Connector: Sized {
|
||||
/// Opens a connection to the given IP socket
|
||||
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<Self>;
|
||||
/// Upgrades to TLS connection
|
||||
@@ -22,7 +21,7 @@ impl Connector for NetworkStream {
|
||||
let tcp_stream = try!(TcpStream::connect(addr));
|
||||
|
||||
match ssl_context {
|
||||
Some(context) => match SslStream::new(&context, tcp_stream) {
|
||||
Some(context) => match SslStream::connect_generic(context, tcp_stream) {
|
||||
Ok(stream) => Ok(NetworkStream::Ssl(stream)),
|
||||
Err(err) => Err(io::Error::new(ErrorKind::Other, err)),
|
||||
},
|
||||
@@ -32,7 +31,7 @@ impl Connector for NetworkStream {
|
||||
|
||||
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()> {
|
||||
*self = match self.clone() {
|
||||
NetworkStream::Plain(stream) => match SslStream::new(ssl_context, stream) {
|
||||
NetworkStream::Plain(stream) => match SslStream::connect_generic(ssl_context, stream) {
|
||||
Ok(ssl_stream) => NetworkStream::Ssl(ssl_stream),
|
||||
Err(err) => return Err(io::Error::new(ErrorKind::Other, err)),
|
||||
},
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! ESMTP features
|
||||
|
||||
use std::result::Result;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::collections::HashSet;
|
||||
|
||||
use transport::smtp::response::Response;
|
||||
use transport::error::Error;
|
||||
use transport::smtp::authentication::Mecanism;
|
||||
use transport::smtp::response::Response;
|
||||
use transport::smtp::authentication::Mechanism;
|
||||
|
||||
/// Supported ESMTP keywords
|
||||
#[derive(PartialEq,Eq,Hash,Clone,Debug)]
|
||||
@@ -24,8 +24,8 @@ pub enum Extension {
|
||||
///
|
||||
/// RFC 2487: https://tools.ietf.org/html/rfc2487
|
||||
StartTls,
|
||||
/// AUTH mecanism
|
||||
Authentication(Mecanism),
|
||||
/// AUTH mechanism
|
||||
Authentication(Mechanism),
|
||||
}
|
||||
|
||||
impl Display for Extension {
|
||||
@@ -34,7 +34,7 @@ impl Display for Extension {
|
||||
Extension::EightBitMime => write!(f, "{}", "8BITMIME"),
|
||||
Extension::SmtpUtfEight => write!(f, "{}", "SMTPUTF8"),
|
||||
Extension::StartTls => write!(f, "{}", "STARTTLS"),
|
||||
Extension::Authentication(ref mecanism) => write!(f, "{} {}", "AUTH", mecanism),
|
||||
Extension::Authentication(ref mechanism) => write!(f, "{} {}", "AUTH", mechanism),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,13 +88,13 @@ impl ServerInfo {
|
||||
features.insert(Extension::StartTls);
|
||||
}
|
||||
"AUTH" => {
|
||||
for &mecanism in &splitted[1..] {
|
||||
match mecanism {
|
||||
for &mechanism in &splitted[1..] {
|
||||
match mechanism {
|
||||
"PLAIN" => {
|
||||
features.insert(Extension::Authentication(Mecanism::Plain));
|
||||
features.insert(Extension::Authentication(Mechanism::Plain));
|
||||
}
|
||||
"CRAM-MD5" => {
|
||||
features.insert(Extension::Authentication(Mecanism::CramMd5));
|
||||
features.insert(Extension::Authentication(Mechanism::CramMd5));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
@@ -116,8 +116,8 @@ impl ServerInfo {
|
||||
}
|
||||
|
||||
/// Checks if the server supports an ESMTP feature
|
||||
pub fn supports_auth_mecanism(&self, mecanism: Mecanism) -> bool {
|
||||
self.features.contains(&Extension::Authentication(mecanism))
|
||||
pub fn supports_auth_mechanism(&self, mechanism: Mechanism) -> bool {
|
||||
self.features.contains(&Extension::Authentication(mechanism))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,15 +125,15 @@ impl ServerInfo {
|
||||
mod test {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{ServerInfo, Extension};
|
||||
use transport::smtp::authentication::Mecanism;
|
||||
use transport::smtp::response::{Code, Response, Severity, Category};
|
||||
use super::{Extension, ServerInfo};
|
||||
use transport::smtp::authentication::Mechanism;
|
||||
use transport::smtp::response::{Category, Code, Response, Severity};
|
||||
|
||||
#[test]
|
||||
fn test_extension_fmt() {
|
||||
assert_eq!(format!("{}", Extension::EightBitMime),
|
||||
"8BITMIME".to_string());
|
||||
assert_eq!(format!("{}", Extension::Authentication(Mecanism::Plain)),
|
||||
assert_eq!(format!("{}", Extension::Authentication(Mechanism::Plain)),
|
||||
"AUTH PLAIN".to_string());
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ mod test {
|
||||
"name with no supported features".to_string());
|
||||
|
||||
let mut plain = HashSet::new();
|
||||
assert!(plain.insert(Extension::Authentication(Mecanism::Plain)));
|
||||
assert!(plain.insert(Extension::Authentication(Mechanism::Plain)));
|
||||
|
||||
assert_eq!(format!("{}",
|
||||
ServerInfo {
|
||||
@@ -190,7 +190,7 @@ mod test {
|
||||
|
||||
assert!(server_info.supports_feature(&Extension::EightBitMime));
|
||||
assert!(!server_info.supports_feature(&Extension::StartTls));
|
||||
assert!(!server_info.supports_auth_mecanism(Mecanism::CramMd5));
|
||||
assert!(!server_info.supports_auth_mechanism(Mechanism::CramMd5));
|
||||
|
||||
let response2 = Response::new(Code::new(Severity::PositiveCompletion,
|
||||
Category::Unspecified4,
|
||||
@@ -202,8 +202,8 @@ mod test {
|
||||
|
||||
let mut features2 = HashSet::new();
|
||||
assert!(features2.insert(Extension::EightBitMime));
|
||||
assert!(features2.insert(Extension::Authentication(Mecanism::Plain)));
|
||||
assert!(features2.insert(Extension::Authentication(Mecanism::CramMd5)));
|
||||
assert!(features2.insert(Extension::Authentication(Mechanism::Plain)));
|
||||
assert!(features2.insert(Extension::Authentication(Mechanism::CramMd5)));
|
||||
|
||||
let server_info2 = ServerInfo {
|
||||
name: "me".to_string(),
|
||||
@@ -213,8 +213,8 @@ mod test {
|
||||
assert_eq!(ServerInfo::from_response(&response2).unwrap(), server_info2);
|
||||
|
||||
assert!(server_info2.supports_feature(&Extension::EightBitMime));
|
||||
assert!(server_info2.supports_auth_mecanism(Mecanism::Plain));
|
||||
assert!(server_info2.supports_auth_mecanism(Mecanism::CramMd5));
|
||||
assert!(server_info2.supports_auth_mechanism(Mechanism::Plain));
|
||||
assert!(server_info2.supports_auth_mechanism(Mechanism::CramMd5));
|
||||
assert!(!server_info2.supports_feature(&Extension::StartTls));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
use std::string::String;
|
||||
use std::net::{SocketAddr, ToSocketAddrs};
|
||||
|
||||
use openssl::ssl::{SslMethod, SslContext};
|
||||
use openssl::ssl::{SslContext, SslMethod};
|
||||
|
||||
use transport::smtp::extension::{Extension, ServerInfo};
|
||||
use transport::error::{EmailResult, Error};
|
||||
use transport::smtp::extension::{Extension, ServerInfo};
|
||||
use transport::smtp::client::Client;
|
||||
use transport::smtp::authentication::Mecanism;
|
||||
use transport::smtp::authentication::Mechanism;
|
||||
use transport::EmailTransport;
|
||||
use email::SendableEmail;
|
||||
|
||||
@@ -47,9 +47,17 @@ pub static NUL: &'static str = "\0";
|
||||
/// TLS security level
|
||||
#[derive(Debug)]
|
||||
pub enum SecurityLevel {
|
||||
/// Only send an email on encrypted connection
|
||||
/// Use a TLS wrapped connection
|
||||
///
|
||||
/// Non RFC-compliant, should only be used if the server does not support STARTTLS.
|
||||
EncryptedWrapper,
|
||||
/// Only send an email on encrypted connection (with STARTTLS)
|
||||
///
|
||||
/// Recommended mode, prevents MITM when used with verified certificates.
|
||||
AlwaysEncrypt,
|
||||
/// Use TLS when available
|
||||
/// Use TLS when available (with STARTTLS)
|
||||
///
|
||||
/// Default mode.
|
||||
Opportunistic,
|
||||
/// Never use TLS
|
||||
NeverEncrypt,
|
||||
@@ -75,8 +83,8 @@ pub struct SmtpTransportBuilder {
|
||||
security_level: SecurityLevel,
|
||||
/// Enable UTF8 mailboxes in enveloppe or headers
|
||||
smtp_utf8: bool,
|
||||
/// List of authentication mecanism, sorted by priority
|
||||
authentication_mecanisms: Vec<Mecanism>,
|
||||
/// List of authentication mechanism, sorted by priority
|
||||
authentication_mechanisms: Vec<Mechanism>,
|
||||
}
|
||||
|
||||
/// Builder for the SMTP SmtpTransport
|
||||
@@ -95,7 +103,7 @@ impl SmtpTransportBuilder {
|
||||
connection_reuse_count_limit: 100,
|
||||
connection_reuse: false,
|
||||
hello_name: "localhost".to_string(),
|
||||
authentication_mecanisms: vec![Mecanism::CramMd5, Mecanism::Plain],
|
||||
authentication_mechanisms: vec![Mechanism::CramMd5, Mechanism::Plain],
|
||||
}),
|
||||
None => Err(From::from("Could nor resolve hostname")),
|
||||
}
|
||||
@@ -112,13 +120,29 @@ impl SmtpTransportBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Require SSL/TLS using STARTTLS
|
||||
/// Set the security level for SSL/TLS
|
||||
pub fn security_level(mut self, level: SecurityLevel) -> SmtpTransportBuilder {
|
||||
self.security_level = level;
|
||||
self
|
||||
}
|
||||
|
||||
/// Require SSL/TLS using STARTTLS
|
||||
///
|
||||
/// Incompatible with `ssl_wrapper()``
|
||||
pub fn encrypt(mut self) -> SmtpTransportBuilder {
|
||||
self.security_level = SecurityLevel::AlwaysEncrypt;
|
||||
self
|
||||
}
|
||||
|
||||
/// Require SSL/TLS using STARTTLS
|
||||
///
|
||||
/// Incompatible with `encrypt()`
|
||||
pub fn ssl_wrapper(mut self) -> SmtpTransportBuilder {
|
||||
self.security_level = SecurityLevel::EncryptedWrapper;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable SMTPUTF8 if the server supports it
|
||||
pub fn smtp_utf8(mut self, enabled: bool) -> SmtpTransportBuilder {
|
||||
self.smtp_utf8 = enabled;
|
||||
self
|
||||
@@ -148,9 +172,9 @@ impl SmtpTransportBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the authentication mecanisms
|
||||
pub fn authentication_mecanisms(mut self, mecanisms: Vec<Mecanism>) -> SmtpTransportBuilder {
|
||||
self.authentication_mecanisms = mecanisms;
|
||||
/// Set the authentication mechanisms
|
||||
pub fn authentication_mechanisms(mut self, mechanisms: Vec<Mechanism>) -> SmtpTransportBuilder {
|
||||
self.authentication_mechanisms = mechanisms;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -260,10 +284,13 @@ impl EmailTransport for SmtpTransport {
|
||||
}
|
||||
}
|
||||
|
||||
// If there is a usable connection, test if the server answers and hello has
|
||||
// been sent
|
||||
if self.state.connection_reuse_count == 0 {
|
||||
try!(self.client.connect(&self.client_info.server_addr));
|
||||
try!(self.client.connect(&self.client_info.server_addr,
|
||||
match &self.client_info.security_level {
|
||||
&SecurityLevel::EncryptedWrapper =>
|
||||
Some(&self.client_info.ssl_context),
|
||||
_ => None,
|
||||
}));
|
||||
|
||||
// Log the connection
|
||||
info!("connection established to {}", self.client_info.server_addr);
|
||||
@@ -276,6 +303,7 @@ impl EmailTransport for SmtpTransport {
|
||||
return Err(From::from("Could not encrypt connection, aborting")),
|
||||
(&SecurityLevel::Opportunistic, false) => (),
|
||||
(&SecurityLevel::NeverEncrypt, _) => (),
|
||||
(&SecurityLevel::EncryptedWrapper, _) => (),
|
||||
(_, true) => {
|
||||
try_smtp!(self.client.starttls(), self);
|
||||
try_smtp!(self.client.upgrade_tls_stream(&self.client_info.ssl_context),
|
||||
@@ -293,16 +321,16 @@ impl EmailTransport for SmtpTransport {
|
||||
|
||||
let mut found = false;
|
||||
|
||||
for mecanism in self.client_info.authentication_mecanisms.clone() {
|
||||
if self.server_info.as_ref().unwrap().supports_auth_mecanism(mecanism) {
|
||||
for mechanism in self.client_info.authentication_mechanisms.clone() {
|
||||
if self.server_info.as_ref().unwrap().supports_auth_mechanism(mechanism) {
|
||||
found = true;
|
||||
try_smtp!(self.client.auth(mecanism, &username, &password), self);
|
||||
try_smtp!(self.client.auth(mechanism, &username, &password), self);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
info!("No supported authentication mecanisms available");
|
||||
info!("No supported authentication mechanisms available");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +276,7 @@ impl Response {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::{Severity, Category, Response, ResponseParser, Code};
|
||||
use super::{Category, Code, Response, ResponseParser, Severity};
|
||||
|
||||
#[test]
|
||||
fn test_severity_from_str() {
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
//! succes
|
||||
|
||||
use transport::error::EmailResult;
|
||||
use transport::smtp::response::Response;
|
||||
use transport::smtp::response::{Category, Code, Response, Severity};
|
||||
use transport::EmailTransport;
|
||||
use transport::smtp::response::{Code, Category, Severity};
|
||||
use email::SendableEmail;
|
||||
|
||||
/// This transport does nothing exept logging the message enveloppe
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::io::Read;
|
||||
|
||||
use lettre::transport::file::FileEmailTransport;
|
||||
use lettre::transport::EmailTransport;
|
||||
use lettre::email::{SendableEmail, EmailBuilder};
|
||||
use lettre::email::{EmailBuilder, SendableEmail};
|
||||
|
||||
#[test]
|
||||
fn file_transport() {
|
||||
@@ -28,7 +28,10 @@ fn file_transport() {
|
||||
let mut buffer = String::new();
|
||||
let _ = f.read_to_string(&mut buffer);
|
||||
|
||||
assert_eq!(buffer, format!("{}: from=<user@localhost> to=<root@localhost>\n{}", message_id, email.message()));
|
||||
assert_eq!(buffer,
|
||||
format!("{}: from=<user@localhost> to=<root@localhost>\n{}",
|
||||
message_id,
|
||||
email.message()));
|
||||
|
||||
remove_file(file).unwrap();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user