Compare commits

...

32 Commits

Author SHA1 Message Date
Alexis Mousset
4efb560bc8 Merge pull request #23 from lettre/update-readme
docs(readme): Update readme for 0.5.0
2015-10-26 21:14:24 +01:00
Alexis Mousset
500c4fb39d Update readme for 0.5.0 2015-10-26 21:05:18 +01:00
Alexis Mousset
d488910010 Merge pull request #22 from lorenz/patch-2
Release version 0.5.0
2015-10-26 21:01:33 +01:00
Lorenz Brun
4155e44dbd Release new version
I'd like to use the new features you introduced in the last few days, especially `transport.send(mail)`. Also the docs are currently built for the `master` branch which means they currently show features not yet available in the Crate.
2015-10-26 20:30:57 +01:00
Alexis Mousset
401118ee68 Improved test for File transport 2015-10-26 00:17:46 +01:00
Alexis Mousset
e6dd9d5a46 Install complete openssl on windows 2015-10-25 23:40:59 +01:00
Alexis Mousset
c8187c4a7c Install packages for kcov 2015-10-25 17:59:56 +01:00
Alexis Mousset
8f211c88a8 Add OpenSSL path to windows build 2015-10-25 17:50:20 +01:00
Alexis Mousset
62df24c5b1 Add file transport 2015-10-25 17:47:07 +01:00
Alexis Mousset
7ac43b73c3 Remove Mailer struct 2015-10-25 15:29:40 +01:00
Alexis Mousset
3c91c065d6 Split integration tests 2015-10-25 12:52:56 +01:00
Alexis Mousset
9e30e7185e Use travis-cargo for benchmarks 2015-10-22 23:52:30 +02:00
Alexis Mousset
4da9e16bfc Add cache for release (used in benchmarks) 2015-10-22 23:51:01 +02:00
Alexis Mousset
2977eb0509 Travis build without sudo 2015-10-22 23:45:20 +02:00
Alexis Mousset
2884da8f90 Use smtp-sink for benchmarks 2015-10-22 23:37:04 +02:00
Alexis Mousset
31a7504d54 Add becnhmarks 2015-10-22 23:34:04 +02:00
Alexis Mousset
9a93feea96 Fix SMTPUTF8 test 2015-10-22 21:51:29 +02:00
Alexis Mousset
f102f321d3 Tests email with travis 2015-10-22 21:45:19 +02:00
Alexis Mousset
1ba47e473c Tests email with travis 2015-10-22 21:41:09 +02:00
Alexis Mousset
3acf21a316 Tests email with travis 2015-10-22 21:32:48 +02:00
Alexis Mousset
544894def9 Add integration testing on travis 2015-10-22 19:30:36 +02:00
Alexis Mousset
f74fb4f89c Add openssl to AppVeyor env 2015-10-22 18:32:00 +02:00
Alexis Mousset
085998c730 Add mingw to AppVeyor 2015-10-22 18:07:20 +02:00
Alexis Mousset
d3d7c4b44e Formatting with rustfmt 2015-10-22 16:53:13 +02:00
Alexis Mousset
88b9cfb847 Fix documentation link 2015-10-21 23:16:09 +02:00
Alexis Mousset
250ed7bcf4 Add SMTPUTF8 support 2015-10-21 23:02:14 +02:00
Alexis Mousset
63d9216df3 Change crate name 2015-10-15 00:03:07 +02:00
Alexis Mousset
54758ebde9 Rename rust-smtp to lettre, add multiple transports support 2015-10-14 23:44:25 +02:00
Alexis Mousset
bd67d80d3e Try to authenticate only once 2015-10-12 23:46:12 +02:00
Alexis Mousset
a91db14869 Configurable TLS security level 2015-10-12 22:47:53 +02:00
Alexis Mousset
b5c6663629 Update AppVeyor configuration 2015-10-12 02:50:53 +02:00
Alexis Mousset
4b4150ed99 Version 0.3.0 2015-10-12 02:20:39 +02:00
23 changed files with 610 additions and 363 deletions

View File

@@ -1,23 +1,15 @@
environment:
CARGO_TARGET: x86_64-pc-windows-gnu
matrix:
- TARGET: x86_64-pc-windows-msvc
- TARGET: i686-pc-windows-gnu
matrix:
- TARGET: x86_64-pc-windows-msvc
- TARGET: x86_64-pc-windows-gnu
install:
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rustc-nightly-${env:TARGET}.tar.gz"
- ps: Start-FileDownload "https://static.rust-lang.org/cargo-dist/cargo-nightly-${env:CARGO_TARGET}.tar.gz"
- 7z x rustc-nightly-%TARGET%.tar.gz > nul
- 7z x rustc-nightly-%TARGET%.tar > nul
- 7z x cargo-nightly-%CARGO_TARGET%.tar.gz > nul
- 7z x cargo-nightly-%CARGO_TARGET%.tar > nul
- call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" amd64
- set PATH=%PATH%;%cd%/rustc-nightly-%TARGET%/rustc/bin
- set PATH=%PATH%;%cd%/cargo-nightly-%CARGO_TARGET%/cargo/bin
- SET PATH=%PATH%;C:\MinGW\bin
- rustc -V
- cargo -V
- ps: Start-FileDownload 'http://slproweb.com/download/Win64OpenSSL-1_0_2d.exe'
- ps: Start-Process "Win64OpenSSL-1_0_2d.exe" -ArgumentList "/silent /verysilent /sp- /suppressmsgboxes" -Wait
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" -FileName "rust-nightly.exe"
- ps: .\rust-nightly.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null
- ps: $env:PATH="$env:PATH;C:\rust\bin"
- rustc -vV
- cargo -vV
build: false
test_script:
- cargo test --verbose --no-default-features
- env OPENSSL_LIB_DIR=C:/OpenSSL-Win64 OPENSSL_INCLUDE_DIR=C:/OpenSSL-Win64/include cargo build --verbose

View File

@@ -1,20 +1,43 @@
language: rust
sudo: required
rust:
- stable
- beta
- nightly
sudo: false
cache:
apt: true
pip: true
directories:
- target/debug/deps
- target/debug/build
- target/release/deps
- target/release/build
install: pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH
addons:
apt:
packages:
- postfix
- libcurl4-openssl-dev
- libelf-dev
- libdw-dev
before_script:
- pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH
- 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
- travis-cargo --only stable coveralls --no-sudo
env:
global:

View File

@@ -1,13 +1,13 @@
[package]
name = "smtp"
version = "0.3.0"
description = "Simple SMTP client"
name = "lettre"
version = "0.5.0"
description = "Email client"
readme = "README.md"
documentation = "http://amousset.me/rust-smtp/smtp/"
repository = "https://github.com/amousset/rust-smtp"
documentation = "http://lettre.github.io/lettre/"
repository = "https://github.com/lettre/lettre"
license = "MIT"
authors = ["Alexis Mousset <alexis.mousset@gmx.fr>"]
authors = ["Alexis Mousset <contact@amousset.me>"]
keywords = ["email", "smtp", "mailer"]
[dependencies]

View File

@@ -1,8 +1,8 @@
rust-smtp [![Build Status](https://travis-ci.org/amousset/rust-smtp.svg?branch=master)](https://travis-ci.org/amousset/rust-smtp) [![Coverage Status](https://coveralls.io/repos/github/amousset/rust-smtp/badge.svg?branch=master)](https://coveralls.io/github/amousset/rust-smtp?branch=master) [![Crate](https://meritbadge.herokuapp.com/smtp)](https://crates.io/crates/smtp) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
lettre [![Build Status](https://travis-ci.org/lettre/lettre.svg?branch=master)](https://travis-ci.org/lettre/lettre) [![Coverage Status](https://coveralls.io/repos/lettre/lettre/badge.svg?branch=master&service=github)](https://coveralls.io/github/lettre/lettre?branch=master) [![Crate](https://meritbadge.herokuapp.com/lettre)](https://crates.io/crates/lettre) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
=========
This library implements a simple SMTP client.
See the [documentation](http://amousset.github.io/rust-smtp/smtp/) for more information.
This is an email library written in Rust.
See the [documentation](http://lettre.github.io/lettre) for more information.
Install
-------
@@ -11,9 +11,14 @@ To use this library, add the following to your `Cargo.toml`:
```toml
[dependencies]
smtp = "0.2"
lettre = "0.5"
```
Testing
-------
The tests require a mail server listening locally on port 25.
License
-------

47
benches/transport_smtp.rs Normal file
View File

@@ -0,0 +1,47 @@
#![feature(test)]
extern crate lettre;
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);
b.iter(|| {
let email = EmailBuilder::new()
.to("root@localhost")
.from("user@localhost")
.body("Hello World!")
.subject("Hello")
.build()
.unwrap();
let result = mailer.send(email);
assert!(result.is_ok());
});
}
#[bench]
fn bench_reuse_send(b: &mut test::Bencher) {
let 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")
.from("user@localhost")
.body("Hello World!")
.subject("Hello")
.build()
.unwrap();
let result = mailer.send(email);
assert!(result.is_ok());
});
mailer.close()
}

View File

@@ -1,54 +0,0 @@
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate smtp;
use std::sync::{Arc, Mutex};
use std::thread;
use smtp::sender::SenderBuilder;
use smtp::email::EmailBuilder;
fn main() {
env_logger::init().unwrap();
let sender = Arc::new(Mutex::new(SenderBuilder::localhost().unwrap().hello_name("localhost")
.enable_connection_reuse(true).build()));
let mut threads = Vec::new();
for _ in 1..5 {
let th_sender = sender.clone();
threads.push(thread::spawn(move || {
let email = EmailBuilder::new()
.to("user@localhost")
.from("user@localhost")
.body("Hello World!")
.subject("Hello")
.build();
let _ = th_sender.lock().unwrap().send(email);
}));
}
for thread in threads {
let _ = thread.join();
}
let email = EmailBuilder::new()
.to("user@localhost")
.from("user@localhost")
.body("Hello World!")
.subject("Hello Bis")
.build();
let mut sender = sender.lock().unwrap();
let result = sender.send(email);
sender.close();
match result {
Ok(..) => info!("Email sent successfully"),
Err(error) => error!("{:?}", error),
}
}

View File

@@ -0,0 +1,20 @@
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());
}

View File

@@ -1,6 +1,7 @@
//! Simple email (very incomplete)
use std::fmt::{Display, Formatter, Result};
use std::fmt::{Display, Formatter};
use std::fmt;
use email_format::{MimeMessage, Header, Mailbox};
use time::{now, Tm};
@@ -53,8 +54,12 @@ impl<'a> ToMailbox for (&'a str, &'a str) {
/// Builds an `Email` structure
#[derive(PartialEq,Eq,Clone,Debug)]
pub struct EmailBuilder {
/// Email content
content: Email,
/// Message
message: MimeMessage,
/// The enveloppe recipients addresses
to: Vec<String>,
/// The enveloppe sender address
from: Option<String>,
/// Date issued
date_issued: bool,
}
@@ -67,13 +72,13 @@ pub struct Email {
/// The enveloppe recipients addresses
to: Vec<String>,
/// The enveloppe sender address
from: Option<String>,
from: String,
/// Message-ID
message_id: Uuid,
}
impl Display for Email {
fn fmt(&self, f: &mut Formatter) -> Result {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.message.as_string())
}
}
@@ -81,30 +86,17 @@ impl Display for Email {
impl EmailBuilder {
/// Creates a new empty email
pub fn new() -> EmailBuilder {
let current_message = Uuid::new_v4();
let mut email = Email {
EmailBuilder {
message: MimeMessage::new_blank_message(),
to: vec![],
from: None,
message_id: current_message,
};
match Header::new_with_value("Message-ID".to_string(),
format!("<{}@rust-smtp>", current_message)) {
Ok(header) => email.message.headers.insert(header),
Err(_) => (),
}
EmailBuilder {
content: email,
date_issued: false,
}
}
/// Sets the email body
pub fn body(mut self, body: &str) -> EmailBuilder {
self.content.message.body = body.to_string();
self.message.body = body.to_string();
self
}
@@ -115,14 +107,14 @@ impl EmailBuilder {
}
fn insert_header<A: ToHeader>(&mut self, header: A) {
self.content.message.headers.insert(header.to_header());
self.message.headers.insert(header.to_header());
}
/// Adds a `From` header and store the sender address
pub fn from<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
let mailbox = address.to_mailbox();
self.insert_header(("From", mailbox.to_string().as_ref()));
self.content.from = Some(mailbox.address);
self.from = Some(mailbox.address);
self
}
@@ -130,7 +122,7 @@ impl EmailBuilder {
pub fn to<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
let mailbox = address.to_mailbox();
self.insert_header(("To", mailbox.to_string().as_ref()));
self.content.to.push(mailbox.address);
self.to.push(mailbox.address);
self
}
@@ -138,7 +130,7 @@ impl EmailBuilder {
pub fn cc<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
let mailbox = address.to_mailbox();
self.insert_header(("Cc", mailbox.to_string().as_ref()));
self.content.to.push(mailbox.address);
self.to.push(mailbox.address);
self
}
@@ -153,7 +145,7 @@ impl EmailBuilder {
pub fn sender<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
let mailbox = address.to_mailbox();
self.insert_header(("Sender", mailbox.to_string().as_ref()));
self.content.from = Some(mailbox.address);
self.from = Some(mailbox.address);
self
}
@@ -171,12 +163,34 @@ impl EmailBuilder {
}
/// Build the Email
pub fn build(mut self) -> Email {
pub fn build(mut self) -> Result<Email, &'static str> {
if self.from.is_none() {
return Err("No from address");
}
if self.to.is_empty() {
return Err("No to address");
}
if !self.date_issued {
self.insert_header(("Date", Tm::rfc822z(&now()).to_string().as_ref()));
}
self.content.message.update_headers();
self.content
let message_id = Uuid::new_v4();
match Header::new_with_value("Message-ID".to_string(),
format!("<{}.lettre@localhost>", message_id)) {
Ok(header) => self.insert_header(header),
Err(_) => (),
}
self.message.update_headers();
Ok(Email {
message: self.message,
to: self.to,
from: self.from.unwrap(),
message_id: message_id,
})
}
}
@@ -184,13 +198,13 @@ impl EmailBuilder {
/// Email sendable by an SMTP client
pub trait SendableEmail {
/// From address
fn from_address(&self) -> Option<String>;
fn from_address(&self) -> String;
/// To addresses
fn to_addresses(&self) -> Option<Vec<String>>;
fn to_addresses(&self) -> Vec<String>;
/// Message content
fn message(&self) -> Option<String>;
fn message(&self) -> String;
/// Message ID
fn message_id(&self) -> Option<String>;
fn message_id(&self) -> String;
}
/// Minimal email structure
@@ -215,47 +229,38 @@ impl SimpleSendableEmail {
}
impl SendableEmail for SimpleSendableEmail {
fn from_address(&self) -> Option<String> {
Some(self.from.clone())
fn from_address(&self) -> String {
self.from.clone()
}
fn to_addresses(&self) -> Option<Vec<String>> {
Some(self.to.clone())
fn to_addresses(&self) -> Vec<String> {
self.to.clone()
}
fn message(&self) -> Option<String> {
Some(self.message.clone())
fn message(&self) -> String {
self.message.clone()
}
fn message_id(&self) -> Option<String> {
Some(format!("<{}@rust-smtp>", Uuid::new_v4()))
fn message_id(&self) -> String {
format!("{}", Uuid::new_v4())
}
}
impl SendableEmail for Email {
/// Return the to addresses, and fails if it is not set
fn to_addresses(&self) -> Option<Vec<String>> {
if self.to.is_empty() {
None
} else {
Some(self.to.clone())
}
fn to_addresses(&self) -> Vec<String> {
self.to.clone()
}
/// Return the from address, and fails if it is not set
fn from_address(&self) -> Option<String> {
match self.from {
Some(ref from_address) => Some(from_address.clone()),
None => None,
}
fn from_address(&self) -> String {
self.from.clone()
}
fn message(&self) -> Option<String> {
Some(format!("{}", self))
fn message(&self) -> String {
format!("{}", self)
}
fn message_id(&self) -> Option<String> {
Some(format!("{}", self.message_id))
fn message_id(&self) -> String {
format!("{}", self.message_id)
}
}
@@ -275,7 +280,7 @@ mod test {
let mut email = Email {
message: MimeMessage::new_blank_message(),
to: vec![],
from: None,
from: "".to_string(),
message_id: current_message,
};
@@ -294,7 +299,7 @@ mod test {
assert_eq!(format!("{}", email),
format!("Message-ID: <{}@rust-smtp>\r\nTo: to@example.com\r\n\r\nbody\r\n",
current_message));
assert_eq!(current_message.to_string(), email.message_id().unwrap());
assert_eq!(current_message.to_string(), email.message_id());
}
#[test]
@@ -311,15 +316,16 @@ mod test {
.date(&date_now)
.subject("Hello")
.add_header(("X-test", "value"))
.build();
.build()
.unwrap();
assert_eq!(format!("{}", email),
format!("Message-ID: <{}@rust-smtp>\r\nTo: <user@localhost>\r\nFrom: \
<user@localhost>\r\nCc: \"Alias\" <cc@localhost>\r\nReply-To: \
<reply@localhost>\r\nSender: <sender@localhost>\r\nDate: \
{}\r\nSubject: Hello\r\nX-test: value\r\n\r\nHello World!\r\n",
email.message_id().unwrap(),
date_now.rfc822z()));
format!("To: <user@localhost>\r\nFrom: <user@localhost>\r\nCc: \"Alias\" \
<cc@localhost>\r\nReply-To: <reply@localhost>\r\nSender: \
<sender@localhost>\r\nDate: {}\r\nSubject: Hello\r\nX-test: \
value\r\nMessage-ID: <{}.lettre@localhost>\r\n\r\nHello World!\r\n",
date_now.rfc822z(),
email.message_id()));
}
#[test]
@@ -336,13 +342,13 @@ mod test {
.date(&date_now)
.subject("Hello")
.add_header(("X-test", "value"))
.build();
.build()
.unwrap();
assert_eq!(email.from_address().unwrap(),
"sender@localhost".to_string());
assert_eq!(email.to_addresses().unwrap(),
assert_eq!(email.from_address(), "sender@localhost".to_string());
assert_eq!(email.to_addresses(),
vec!["user@localhost".to_string(), "cc@localhost".to_string()]);
assert_eq!(email.message().unwrap(), format!("{}", email));
assert_eq!(email.message(), format!("{}", email));
}
}

View File

@@ -1,26 +1,27 @@
//! # Rust SMTP client
//! # Rust email client
//!
//! This client should tend to follow [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
//! relay email server, as it relies as much as possible on the relay server for sanity and RFC
//! This client should tend to follow [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
//! relay email server, as it relies as much as possible on the relay server
//! for sanity and RFC
//! compliance checks.
//!
//! It implements the following extensions:
//!
//! * 8BITMIME ([RFC 6152](https://tools.ietf.org/html/rfc6152))
//! * AUTH ([RFC 4954](http://tools.ietf.org/html/rfc4954)) with PLAIN and CRAM-MD5 mecanisms
//! * AUTH ([RFC 4954](http://tools.ietf.org/html/rfc4954)) with PLAIN and
//! CRAM-MD5 mecanisms
//! * STARTTLS ([RFC 2487](http://tools.ietf.org/html/rfc2487))
//!
//! It will eventually implement the following extensions:
//!
//! * SMTPUTF8 ([RFC 6531](http://tools.ietf.org/html/rfc6531))
//!
//! ## Architecture
//!
//! This client is divided into three main parts:
//!
//! * client: a low level SMTP client providing all SMTP commands
//! * sender: a high level SMTP client providing an easy method to send emails
//! * 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
@@ -29,9 +30,10 @@
//!
//! This is the most basic example of usage:
//!
//! ```rust,no_run
//! use smtp::sender::{Sender, SenderBuilder};
//! use smtp::email::EmailBuilder;
//! ```rust
//! use lettre::transport::smtp::{SmtpTransport, SmtpTransportBuilder};
//! use lettre::email::EmailBuilder;
//! use lettre::transport::EmailTransport;
//!
//! // Create an email
//! let email = EmailBuilder::new()
@@ -41,12 +43,13 @@
//! .from("user@example.com")
//! .subject("Hi, Hello world")
//! .body("Hello world.")
//! .build();
//! .build().unwrap();
//!
//! // Open a local connection on port 25
//! let mut sender = SenderBuilder::localhost().unwrap().build();
//! let mut mailer =
//! SmtpTransportBuilder::localhost().unwrap().build();
//! // Send the email
//! let result = sender.send(email);
//! let result = mailer.send(email);
//!
//! assert!(result.is_ok());
//! ```
@@ -54,10 +57,12 @@
//! ### Complete example
//!
//! ```rust,no_run
//! use smtp::sender::{Sender, SenderBuilder};
//! use smtp::email::EmailBuilder;
//! use smtp::authentication::Mecanism;
//! use smtp::SUBMISSION_PORT;
//! use lettre::email::EmailBuilder;
//! use lettre::transport::smtp::{SecurityLevel, SmtpTransport,
//! SmtpTransportBuilder};
//! use lettre::transport::smtp::authentication::Mecanism;
//! use lettre::transport::smtp::SUBMISSION_PORT;
//! use lettre::transport::EmailTransport;
//!
//! let mut builder = EmailBuilder::new();
//! builder = builder.to(("user@example.org", "Alias name"));
@@ -70,40 +75,44 @@
//! builder = builder.reply_to("contact@example.com");
//! builder = builder.add_header(("X-Custom-Header", "my header"));
//!
//! let email = builder.build();
//! let email = builder.build().unwrap();
//!
//! // Connect to a remote server on a custom port
//! let mut sender = SenderBuilder::new(("server.tld", SUBMISSION_PORT)).unwrap()
//! let mut mailer = SmtpTransportBuilder::new(("server.tld",
//! SUBMISSION_PORT)).unwrap()
//! // Set the name sent during EHLO/HELO, default is `localhost`
//! .hello_name("my.hostname.tld")
//! // Add credentials for authentication
//! .credentials("username", "password")
//! // Use TLS with STARTTLS, you can also specify a specific SSL context
//! // with `.ssl_context(context)`
//! .starttls()
//! // Specify a TLS security level. You can also specify an SslContext with
//! // .ssl_context(SslContext::Ssl23)
//! .security_level(SecurityLevel::AlwaysEncrypt)
//! // Enable SMTPUTF8 is the server supports it
//! .smtp_utf8(true)
//! // Configure accepted authetication mecanisms
//! .authentication_mecanisms(vec![Mecanism::CramMd5])
//! // Enable connection reuse
//! .enable_connection_reuse(true).build();
//! .connection_reuse(true).build();
//!
//! let result_1 = sender.send(email.clone());
//! let result_1 = mailer.send(email.clone());
//! assert!(result_1.is_ok());
//!
//! // The second email will use the same connection
//! let result_2 = sender.send(email);
//! let result_2 = mailer.send(email);
//! assert!(result_2.is_ok());
//!
//! // Explicitely close the SMTP transaction as we enabled connection reuse
//! sender.close();
//! mailer.close();
//! ```
//!
//! ### Using the client directly
//!
//! If you just want to send an email without using `Email` to provide headers:
//!
//! ```rust,no_run
//! use smtp::sender::{Sender, SenderBuilder};
//! use smtp::email::SimpleSendableEmail;
//! ```rust
//! use lettre::email::SimpleSendableEmail;
//! use lettre::transport::smtp::{SmtpTransport, SmtpTransportBuilder};
//! use lettre::transport::EmailTransport;
//!
//! // Create a minimal email
//! let email = SimpleSendableEmail::new(
@@ -112,19 +121,21 @@
//! "Hello world !"
//! );
//!
//! let mut sender = SenderBuilder::localhost().unwrap().build();
//! let result = sender.send(email);
//! 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 error handling:
//! You can also send commands, here is a simple email transaction without
//! error handling:
//!
//! ```rust,no_run
//! use smtp::client::Client;
//! use smtp::SMTP_PORT;
//! use smtp::client::net::NetworkStream;
//! ```rust
//! use lettre::transport::smtp::SMTP_PORT;
//! use lettre::transport::smtp::client::Client;
//! use lettre::transport::smtp::client::net::NetworkStream;
//!
//! let mut email_client: Client<NetworkStream> = Client::new();
//! let _ = email_client.connect(&("localhost", SMTP_PORT));
@@ -140,7 +151,7 @@
#[macro_use]
extern crate log;
extern crate rustc_serialize as serialize;
extern crate rustc_serialize;
extern crate crypto;
extern crate time;
extern crate uuid;
@@ -148,39 +159,5 @@ extern crate email as email_format;
extern crate bufstream;
extern crate openssl;
mod extension;
pub mod client;
pub mod sender;
pub mod response;
pub mod error;
pub mod authentication;
pub mod transport;
pub mod email;
// Registrated port numbers:
// https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
/// Default smtp port
pub static SMTP_PORT: u16 = 25;
/// Default smtps port
pub static SMTPS_PORT: u16 = 465;
/// Default submission port
pub static SUBMISSION_PORT: u16 = 587;
// Useful strings and characters
/// The word separator for SMTP transactions
pub static SP: &'static str = " ";
/// The line ending for SMTP transactions (carriage return + line feed)
pub static CRLF: &'static str = "\r\n";
/// Colon
pub static COLON: &'static str = ":";
/// The ending of message content
pub static MESSAGE_ENDING: &'static str = "\r\n.\r\n";
/// NUL unicode character
pub static NUL: &'static str = "\0";

View File

@@ -5,8 +5,8 @@ use std::io;
use std::fmt::{Display, Formatter};
use std::fmt;
use response::{Severity, Response};
use serialize::base64::FromBase64Error;
use transport::smtp::response::{Severity, Response};
use rustc_serialize::base64::FromBase64Error;
use self::Error::*;
/// An enum of all error kinds.
@@ -82,9 +82,4 @@ impl From<&'static str> for Error {
}
/// SMTP result type
pub type SmtpResult = Result<Response, Error>;
#[cfg(test)]
mod test {
// TODO
}
pub type EmailResult = Result<Response, Error>;

53
src/transport/file/mod.rs Normal file
View File

@@ -0,0 +1,53 @@
//! TODO
use std::path::{Path, PathBuf};
use std::io::prelude::*;
use std::fs::File;
use transport::error::EmailResult;
use transport::smtp::response::Response;
use transport::EmailTransport;
use transport::smtp::response::{Code, Category, Severity};
use email::SendableEmail;
/// TODO
pub struct FileEmailTransport {
path: PathBuf,
}
impl FileEmailTransport {
/// Creates a new transport to the given directory
pub fn new<P: AsRef<Path>>(path: P) -> FileEmailTransport {
let mut path_buf = PathBuf::new();
path_buf.push(path);
FileEmailTransport { path: path_buf }
}
}
impl EmailTransport for FileEmailTransport {
fn send<T: SendableEmail>(&mut self, email: T) -> EmailResult {
let mut file = self.path.clone();
file.push(format!("{}.txt", email.message_id()));
let mut f = try!(File::create(file.as_path()));
let log_line = format!("{}: from=<{}> to=<{}>\n",
email.message_id(),
email.from_address(),
email.to_addresses().join("> to=<"));
try!(f.write_all(log_line.as_bytes()));
try!(f.write_all(format!("{}", email.message()).as_bytes()));
info!("{} status=<written>", log_line);
Ok(Response::new(Code::new(Severity::PositiveCompletion, Category::MailSystem, 0),
vec![format!("Ok: email written to {}",
file.to_str().unwrap_or("non-UTF-8 path"))]))
}
fn close(&mut self) {
()
}
}

16
src/transport/mod.rs Normal file
View File

@@ -0,0 +1,16 @@
//! Represents an Email transport
pub mod smtp;
pub mod error;
pub mod stub;
pub mod file;
use transport::error::EmailResult;
use email::SendableEmail;
/// Transport method for emails
pub trait EmailTransport {
/// Sends the email
fn send<T: SendableEmail>(&mut self, email: T) -> EmailResult;
/// Close the transport explicitely
fn close(&mut self);
}

View File

@@ -3,14 +3,14 @@
use std::fmt::{Display, Formatter};
use std::fmt;
use serialize::base64::{self, ToBase64, FromBase64};
use serialize::hex::ToHex;
use rustc_serialize::base64::{self, ToBase64, FromBase64};
use rustc_serialize::hex::ToHex;
use crypto::hmac::Hmac;
use crypto::md5::Md5;
use crypto::mac::Mac;
use NUL;
use error::Error;
use transport::smtp::NUL;
use transport::error::Error;
/// Represents authentication mecanisms
#[derive(PartialEq,Eq,Copy,Clone,Hash,Debug)]

View File

@@ -9,11 +9,11 @@ use std::fmt::Debug;
use bufstream::BufStream;
use openssl::ssl::SslContext;
use response::ResponseParser;
use authentication::Mecanism;
use error::{Error, SmtpResult};
use client::net::{Connector, NetworkStream};
use {CRLF, MESSAGE_ENDING};
use transport::smtp::response::ResponseParser;
use transport::smtp::authentication::Mecanism;
use transport::error::{Error, EmailResult};
use transport::smtp::client::net::{Connector, NetworkStream};
use transport::smtp::{CRLF, MESSAGE_ENDING};
pub mod net;
@@ -27,8 +27,8 @@ fn escape_dot(string: &str) -> String {
} else {
string.to_string()
}
.replace("\r.", "\r..")
.replace("\n.", "\n..")
.replace("\r.", "\r..")
.replace("\n.", "\n..")
}
/// Returns the string replacing all the CRLF with "\<CRLF\>"
@@ -44,6 +44,7 @@ fn remove_crlf(string: &str) -> String {
}
/// Structure that implements the SMTP client
#[derive(Debug)]
pub struct Client<S: Write + Read = NetworkStream> {
/// TCP stream between client and server
/// Value is None before connection
@@ -79,7 +80,6 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
/// Upgrades the underlying connection to SSL/TLS
pub fn upgrade_tls_stream(&mut self, ssl_context: &SslContext) -> io::Result<()> {
//let current_stream = self.stream.clone();
if self.stream.is_some() {
self.stream.as_mut().unwrap().get_mut().upgrade_tls(ssl_context)
} else {
@@ -88,7 +88,7 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Connects to the configured server
pub fn connect<A: ToSocketAddrs>(&mut self, addr: &A) -> SmtpResult {
pub fn connect<A: ToSocketAddrs>(&mut self, addr: &A) -> 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);
@@ -113,17 +113,17 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Sends an SMTP command
pub fn command(&mut self, command: &str) -> SmtpResult {
pub fn command(&mut self, command: &str) -> EmailResult {
self.send_server(command, CRLF)
}
/// Sends a EHLO command
pub fn ehlo(&mut self, hostname: &str) -> SmtpResult {
pub fn ehlo(&mut self, hostname: &str) -> EmailResult {
self.command(&format!("EHLO {}", hostname))
}
/// Sends a MAIL command
pub fn mail(&mut self, address: &str, options: Option<&str>) -> SmtpResult {
pub fn mail(&mut self, address: &str, options: Option<&str>) -> EmailResult {
match options {
Some(ref options) => self.command(&format!("MAIL FROM:<{}> {}", address, options)),
None => self.command(&format!("MAIL FROM:<{}>", address)),
@@ -131,27 +131,27 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Sends a RCPT command
pub fn rcpt(&mut self, address: &str) -> SmtpResult {
pub fn rcpt(&mut self, address: &str) -> EmailResult {
self.command(&format!("RCPT TO:<{}>", address))
}
/// Sends a DATA command
pub fn data(&mut self) -> SmtpResult {
pub fn data(&mut self) -> EmailResult {
self.command("DATA")
}
/// Sends a QUIT command
pub fn quit(&mut self) -> SmtpResult {
pub fn quit(&mut self) -> EmailResult {
self.command("QUIT")
}
/// Sends a NOOP command
pub fn noop(&mut self) -> SmtpResult {
pub fn noop(&mut self) -> EmailResult {
self.command("NOOP")
}
/// Sends a HELP command
pub fn help(&mut self, argument: Option<&str>) -> SmtpResult {
pub fn help(&mut self, argument: Option<&str>) -> EmailResult {
match argument {
Some(ref argument) => self.command(&format!("HELP {}", argument)),
None => self.command("HELP"),
@@ -159,22 +159,22 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Sends a VRFY command
pub fn vrfy(&mut self, address: &str) -> SmtpResult {
pub fn vrfy(&mut self, address: &str) -> EmailResult {
self.command(&format!("VRFY {}", address))
}
/// Sends a EXPN command
pub fn expn(&mut self, address: &str) -> SmtpResult {
pub fn expn(&mut self, address: &str) -> EmailResult {
self.command(&format!("EXPN {}", address))
}
/// Sends a RSET command
pub fn rset(&mut self) -> SmtpResult {
pub fn rset(&mut self) -> EmailResult {
self.command("RSET")
}
/// Sends an AUTH command with the given mecanism
pub fn auth(&mut self, mecanism: Mecanism, username: &str, password: &str) -> SmtpResult {
pub fn auth(&mut self, mecanism: Mecanism, username: &str, password: &str) -> EmailResult {
if mecanism.supports_initial_response() {
self.command(&format!("AUTH {} {}",
@@ -197,17 +197,17 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Sends a STARTTLS command
pub fn starttls(&mut self) -> SmtpResult {
pub fn starttls(&mut self) -> EmailResult {
self.command("STARTTLS")
}
/// Sends the message content
pub fn message(&mut self, message_content: &str) -> SmtpResult {
pub fn message(&mut self, message_content: &str) -> EmailResult {
self.send_server(&escape_dot(message_content), MESSAGE_ENDING)
}
/// Sends a string to the server and gets the response
fn send_server(&mut self, string: &str, end: &str) -> SmtpResult {
fn send_server(&mut self, string: &str, end: &str) -> EmailResult {
if self.stream.is_none() {
return Err(From::from("Connection closed"));
}
@@ -221,7 +221,7 @@ impl<S: Connector + Write + Read + Debug + Clone = NetworkStream> Client<S> {
}
/// Gets the SMTP response
fn get_reply(&mut self) -> SmtpResult {
fn get_reply(&mut self) -> EmailResult {
let mut parser = ResponseParser::new();

View File

@@ -6,6 +6,7 @@ use std::net::SocketAddr;
use std::net::TcpStream;
use std::fmt;
use std::fmt::{Debug, Formatter};
use openssl::ssl::{SslContext, SslStream};
/// A trait for the concept of opening a stream

View File

@@ -5,9 +5,9 @@ use std::fmt::{Display, Formatter};
use std::fmt;
use std::collections::HashSet;
use response::Response;
use error::Error;
use authentication::Mecanism;
use transport::smtp::response::Response;
use transport::error::Error;
use transport::smtp::authentication::Mecanism;
/// Supported ESMTP keywords
#[derive(PartialEq,Eq,Hash,Clone,Debug)]
@@ -126,8 +126,8 @@ mod test {
use std::collections::HashSet;
use super::{ServerInfo, Extension};
use authentication::Mecanism;
use response::{Code, Response, Severity, Category};
use transport::smtp::authentication::Mecanism;
use transport::smtp::response::{Code, Response, Severity, Category};
#[test]
fn test_extension_fmt() {

View File

@@ -5,21 +5,64 @@ use std::net::{SocketAddr, ToSocketAddrs};
use openssl::ssl::{SslMethod, SslContext};
use SMTP_PORT;
use extension::{Extension, ServerInfo};
use error::{SmtpResult, Error};
use transport::smtp::extension::{Extension, ServerInfo};
use transport::error::{EmailResult, Error};
use transport::smtp::client::Client;
use transport::smtp::authentication::Mecanism;
use transport::EmailTransport;
use email::SendableEmail;
use client::Client;
use authentication::Mecanism;
pub mod extension;
pub mod authentication;
pub mod response;
pub mod client;
// Registrated port numbers:
// https://www.iana.
// org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
/// Default smtp port
pub static SMTP_PORT: u16 = 25;
/// Default submission port
pub static SUBMISSION_PORT: u16 = 587;
// Useful strings and characters
/// The word separator for SMTP transactions
pub static SP: &'static str = " ";
/// The line ending for SMTP transactions (carriage return + line feed)
pub static CRLF: &'static str = "\r\n";
/// Colon
pub static COLON: &'static str = ":";
/// The ending of message content
pub static MESSAGE_ENDING: &'static str = "\r\n.\r\n";
/// NUL unicode character
pub static NUL: &'static str = "\0";
/// TLS security level
#[derive(Debug)]
pub enum SecurityLevel {
/// Only send an email on encrypted connection
AlwaysEncrypt,
/// Use TLS when available
Opportunistic,
/// Never use TLS
NeverEncrypt,
}
/// Contains client configuration
pub struct SenderBuilder {
pub struct SmtpTransportBuilder {
/// Maximum connection reuse
///
/// Zero means no limitation
connection_reuse_count_limit: u16,
/// Enable connection reuse
enable_connection_reuse: bool,
connection_reuse: bool,
/// Name sent during HELO or EHLO
hello_name: String,
/// Credentials
@@ -27,24 +70,30 @@ pub struct SenderBuilder {
/// Socket we are connecting to
server_addr: SocketAddr,
/// SSL contexyt to use
ssl_context: Option<SslContext>,
ssl_context: SslContext,
/// TLS security level
security_level: SecurityLevel,
/// Enable UTF8 mailboxes in enveloppe or headers
smtp_utf8: bool,
/// List of authentication mecanism, sorted by priority
authentication_mecanisms: Vec<Mecanism>,
}
/// Builder for the SMTP Sender
impl SenderBuilder {
/// Builder for the SMTP SmtpTransport
impl SmtpTransportBuilder {
/// Creates a new local SMTP client
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<SenderBuilder, Error> {
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<SmtpTransportBuilder, Error> {
let mut addresses = try!(addr.to_socket_addrs());
match addresses.next() {
Some(addr) => Ok(SenderBuilder {
Some(addr) => Ok(SmtpTransportBuilder {
server_addr: addr,
ssl_context: None,
ssl_context: SslContext::new(SslMethod::Tlsv1).unwrap(),
security_level: SecurityLevel::Opportunistic,
smtp_utf8: false,
credentials: None,
connection_reuse_count_limit: 100,
enable_connection_reuse: false,
connection_reuse: false,
hello_name: "localhost".to_string(),
authentication_mecanisms: vec![Mecanism::CramMd5, Mecanism::Plain],
}),
@@ -53,56 +102,63 @@ impl SenderBuilder {
}
/// Creates a new local SMTP client to port 25
pub fn localhost() -> Result<SenderBuilder, Error> {
SenderBuilder::new(("localhost", SMTP_PORT))
pub fn localhost() -> Result<SmtpTransportBuilder, Error> {
SmtpTransportBuilder::new(("localhost", SMTP_PORT))
}
/// Use STARTTLS with a specific context
pub fn ssl_context(mut self, ssl_context: SslContext) -> SenderBuilder {
self.ssl_context = Some(ssl_context);
pub fn ssl_context(mut self, ssl_context: SslContext) -> SmtpTransportBuilder {
self.ssl_context = ssl_context;
self
}
/// Require SSL/TLS using STARTTLS
pub fn starttls(self) -> SenderBuilder {
self.ssl_context(SslContext::new(SslMethod::Tlsv1).unwrap())
pub fn security_level(mut self, level: SecurityLevel) -> SmtpTransportBuilder {
self.security_level = level;
self
}
/// Require SSL/TLS using STARTTLS
pub fn smtp_utf8(mut self, enabled: bool) -> SmtpTransportBuilder {
self.smtp_utf8 = enabled;
self
}
/// Set the name used during HELO or EHLO
pub fn hello_name(mut self, name: &str) -> SenderBuilder {
pub fn hello_name(mut self, name: &str) -> SmtpTransportBuilder {
self.hello_name = name.to_string();
self
}
/// Enable connection reuse
pub fn enable_connection_reuse(mut self, enable: bool) -> SenderBuilder {
self.enable_connection_reuse = enable;
pub fn connection_reuse(mut self, enable: bool) -> SmtpTransportBuilder {
self.connection_reuse = enable;
self
}
/// Set the maximum number of emails sent using one connection
pub fn connection_reuse_count_limit(mut self, limit: u16) -> SenderBuilder {
pub fn connection_reuse_count_limit(mut self, limit: u16) -> SmtpTransportBuilder {
self.connection_reuse_count_limit = limit;
self
}
/// Set the client credentials
pub fn credentials(mut self, username: &str, password: &str) -> SenderBuilder {
pub fn credentials(mut self, username: &str, password: &str) -> SmtpTransportBuilder {
self.credentials = Some((username.to_string(), password.to_string()));
self
}
/// Set the authentication mecanisms
pub fn authentication_mecanisms(mut self, mecanisms: Vec<Mecanism>) -> SenderBuilder {
pub fn authentication_mecanisms(mut self, mecanisms: Vec<Mecanism>) -> SmtpTransportBuilder {
self.authentication_mecanisms = mecanisms;
self
}
/// Build the SMTP client
///
/// It does not connects to the server, but only creates the `Sender`
pub fn build(self) -> Sender {
Sender::new(self)
/// It does not connects to the server, but only creates the `SmtpTransport`
pub fn build(self) -> SmtpTransport {
SmtpTransport::new(self)
}
}
@@ -116,14 +172,14 @@ struct State {
}
/// Structure that implements the high level SMTP client
pub struct Sender {
pub struct SmtpTransport {
/// Information about the server
/// Value is None before HELO/EHLO
server_info: Option<ServerInfo>,
/// Sender variable states
/// SmtpTransport variable states
state: State,
/// Information about the client
client_info: SenderBuilder,
client_info: SmtpTransportBuilder,
/// Low level client
client: Client,
}
@@ -137,21 +193,21 @@ macro_rules! try_smtp (
$client.state.panic = true;
$client.reset();
}
return Err(err)
return Err(From::from(err))
},
}
})
);
impl Sender {
impl SmtpTransport {
/// Creates a new SMTP client
///
/// It does not connects to the server, but only creates the `Sender`
pub fn new(builder: SenderBuilder) -> Sender {
/// It does not connects to the server, but only creates the `SmtpTransport`
pub fn new(builder: SmtpTransportBuilder) -> SmtpTransport {
let client = Client::new();
Sender {
SmtpTransport {
client: client,
server_info: None,
client_info: builder,
@@ -173,13 +229,8 @@ impl Sender {
self.state.connection_reuse_count = 0;
}
/// Closes the inner connection
pub fn close(&mut self) {
self.client.close();
}
/// Gets the EHLO response and updates server information
pub fn get_ehlo(&mut self) -> SmtpResult {
pub fn get_ehlo(&mut self) -> EmailResult {
// Extended Hello
let ehlo_response = try_smtp!(self.client.ehlo(&self.client_info.hello_name), self);
@@ -190,9 +241,18 @@ impl Sender {
Ok(ehlo_response)
}
}
impl EmailTransport for SmtpTransport {
/// Sends an email
pub fn send<T: SendableEmail>(&mut self, email: T) -> SmtpResult {
fn send<T: SendableEmail>(&mut self, email: T) -> EmailResult {
// Extract email information
let message_id = email.message_id();
let from_address = email.from_address();
let to_addresses = email.to_addresses();
let message = email.message();
// Check if the connection is still available
if self.state.connection_reuse_count > 0 {
if !self.client.is_connected() {
@@ -200,7 +260,8 @@ impl Sender {
}
}
// If there is a usable connection, test if the server answers and hello has been sent
// 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));
@@ -209,16 +270,25 @@ impl Sender {
try!(self.get_ehlo());
if self.client_info.ssl_context.is_some() {
try_smtp!(self.client.starttls(), self);
match (&self.client_info.security_level,
self.server_info.as_ref().unwrap().supports_feature(&Extension::StartTls)) {
(&SecurityLevel::AlwaysEncrypt, false) =>
return Err(From::from("Could not encrypt connection, aborting")),
(&SecurityLevel::Opportunistic, false) => (),
(&SecurityLevel::NeverEncrypt, _) => (),
(_, true) => {
try_smtp!(self.client.starttls(), self);
try_smtp!(self.client.upgrade_tls_stream(&self.client_info.ssl_context),
self);
try!(self.client
.upgrade_tls_stream(self.client_info.ssl_context.as_ref().unwrap()));
debug!("connection encrypted");
try!(self.get_ehlo());
// Send EHLO again
try!(self.get_ehlo());
}
}
if self.client_info.credentials.is_some() && self.state.connection_reuse_count == 0 {
if self.client_info.credentials.is_some() {
let (username, password) = self.client_info.credentials.clone().unwrap();
let mut found = false;
@@ -226,41 +296,41 @@ impl Sender {
for mecanism in self.client_info.authentication_mecanisms.clone() {
if self.server_info.as_ref().unwrap().supports_auth_mecanism(mecanism) {
found = true;
let result = self.client.auth(mecanism, &username, &password);
try_smtp!(result, self);
try_smtp!(self.client.auth(mecanism, &username, &password), self);
break;
}
}
if !found {
debug!("No supported authentication mecanisms available");
info!("No supported authentication mecanisms available");
}
}
}
let current_message = try!(email.message_id().ok_or("Missing Message-ID"));
let from_address = try!(email.from_address().ok_or("Missing From address"));
let to_addresses = try!(email.to_addresses().ok_or("Missing To address"));
let message = try!(email.message().ok_or("Missing message"));
// Mail
let mail_options = match self.server_info
.as_ref()
.unwrap()
.supports_feature(&Extension::EightBitMime) {
true => Some("BODY=8BITMIME"),
false => None,
let mail_options = match (self.server_info
.as_ref()
.unwrap()
.supports_feature(&Extension::EightBitMime),
self.server_info
.as_ref()
.unwrap()
.supports_feature(&Extension::SmtpUtfEight)) {
(true, true) => Some("BODY=8BITMIME SMTPUTF8"),
(true, false) => Some("BODY=8BITMIME"),
(false, _) => None,
};
try_smtp!(self.client.mail(&from_address, mail_options), self);
// Log the mail command
info!("{}: from=<{}>", current_message, from_address);
info!("{}: from=<{}>", message_id, from_address);
// Recipient
for to_address in to_addresses.iter() {
try_smtp!(self.client.rcpt(&to_address), self);
// Log the rcpt command
info!("{}: to=<{}>", current_message, to_address);
info!("{}: to=<{}>", message_id, to_address);
}
// Data
@@ -275,7 +345,7 @@ impl Sender {
// Log the message
info!("{}: conn_use={}, size={}, status=sent ({})",
current_message,
message_id,
self.state.connection_reuse_count,
message.len(),
result.as_ref()
@@ -288,11 +358,16 @@ impl Sender {
}
// Test if we can reuse the existing connection
if (!self.client_info.enable_connection_reuse) ||
if (!self.client_info.connection_reuse) ||
(self.state.connection_reuse_count >= self.client_info.connection_reuse_count_limit) {
self.reset();
}
result
}
/// Closes the inner connection
fn close(&mut self) {
self.client.close();
}
}

View File

@@ -1,4 +1,5 @@
//! SMTP response, containing a mandatory return code and an optional text message
//! SMTP response, containing a mandatory return code and an optional text
//! message
use std::str::FromStr;
use std::fmt::{Display, Formatter, Result};
@@ -6,7 +7,7 @@ use std::result;
use self::Severity::*;
use self::Category::*;
use error::{SmtpResult, Error};
use transport::error::{EmailResult, Error};
/// First digit indicates severity
#[derive(PartialEq,Eq,Copy,Clone,Debug)]
@@ -192,7 +193,7 @@ impl ResponseParser {
}
/// Builds a response from a `ResponseParser`
pub fn response(self) -> SmtpResult {
pub fn response(self) -> EmailResult {
match self.code {
Some(code) => Ok(Response::new(code, self.message)),
None => Err(Error::ResponseParsingError("Incomplete response, could not read \

27
src/transport/stub/mod.rs Normal file
View File

@@ -0,0 +1,27 @@
//! This transport is a stub that only logs the message, and always returns
//! succes
use transport::error::EmailResult;
use transport::smtp::response::Response;
use transport::EmailTransport;
use transport::smtp::response::{Code, Category, Severity};
use email::SendableEmail;
/// This transport does nothing exept logging the message enveloppe
pub struct StubEmailTransport;
impl EmailTransport for StubEmailTransport {
fn send<T: SendableEmail>(&mut self, email: T) -> EmailResult {
info!("{}: from=<{}> to=<{:?}>",
email.message_id(),
email.from_address(),
email.to_addresses());
Ok(Response::new(Code::new(Severity::PositiveCompletion, Category::MailSystem, 0),
vec!["Ok: email logged".to_string()]))
}
fn close(&mut self) {
()
}
}

View File

@@ -1,14 +1,5 @@
// Copyright 2014 Alexis Mousset. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate lettre;
#[test]
fn foo() {
assert!(true);
}
mod transport_smtp;
mod transport_stub;
mod transport_file;

34
tests/transport_file.rs Normal file
View File

@@ -0,0 +1,34 @@
extern crate lettre;
use std::env::temp_dir;
use std::fs::File;
use std::fs::remove_file;
use std::io::Read;
use lettre::transport::file::FileEmailTransport;
use lettre::transport::EmailTransport;
use lettre::email::{SendableEmail, EmailBuilder};
#[test]
fn file_transport() {
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.clone());
assert!(result.is_ok());
let message_id = email.message_id();
let file = format!("{}/{}.txt", temp_dir().to_str().unwrap(), message_id);
let mut f = File::open(file.clone()).unwrap();
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()));
remove_file(file).unwrap();
}

19
tests/transport_smtp.rs Normal file
View File

@@ -0,0 +1,19 @@
extern crate lettre;
use lettre::transport::smtp::SmtpTransportBuilder;
use lettre::transport::EmailTransport;
use lettre::email::EmailBuilder;
#[test]
fn simple_sender() {
let mut sender = SmtpTransportBuilder::localhost().unwrap().build();
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());
}

19
tests/transport_stub.rs Normal file
View File

@@ -0,0 +1,19 @@
extern crate lettre;
use lettre::transport::stub::StubEmailTransport;
use lettre::transport::EmailTransport;
use lettre::email::EmailBuilder;
#[test]
fn stub_transport() {
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());
}