如何在rust中发送邮件?OK,我们会用到下面两个第三方依赖:
step1 (add dependencies)
[dependencies]
lettre = "0.8"
lettre_email = "0.8.0"
extern crate lettre;
extern crate lettre_email;
step2 (create EmailBuilder)
let email = EmailBuilder::new()
// Addresses can be specified by the tuple (email, alias)
.to(("user@example.org", "Firstname Lastname"))
// ... or by an address only
.from("user@example.com")
.subject("Hi, Hello world")
.text("Hello world.")
.attachment(Path::new("Cargo.toml"), None, &mime::TEXT_PLAIN).unwrap()
.build()
.unwrap();
step3 (create mailer)
let mut mailer = SmtpTransport::simple_builder(domian).unwrap()
.smtp_utf8(true)
.hello_name(ClientId::Domain("localhost".to_string()))
.credentials(Credentials::new(send_from.to_string(), passwd.to_string()))
.smtp_utf8(true)
.authentication_mechanism(Mechanism::Plain)
.connection_reuse(ConnectionReuseParameters::ReuseUnlimited).build();
step4 (send & closed)
let result = mailer.send(&email);
if !result.is_ok() {
println!("send_email() get error: {:#?}", result);
}
mailer.close();
完整代码
extern crate lettre;
extern crate lettre_email;
use lettre_email::EmailBuilder;
use lettre::smtp::authentication::{Credentials, Mechanism};
use lettre::smtp::extension::ClientId;
use lettre::EmailTransport;
use lettre::SmtpTransport;
use lettre::smtp::ConnectionReuseParameters;
fn main() {
let send_to = vec!["xxx@qq.com", "xxx@sina.com"];
let send_from = "xxx@sina.com";
let passwd = "xxx";
let subject = "mail subject";
let body = "mail body test";
let domian = "xxxxxx";//smtp.sina.com
//=======
let mut builder = EmailBuilder::new();
for to in send_to {
builder.add_to(to);
}
builder.add_from(send_from);
builder.set_subject(subject);
builder.set_body(body);
let email = builder.build().unwrap();
let mut mailer = SmtpTransport::simple_builder(domian).unwrap()
.smtp_utf8(true)
.hello_name(ClientId::Domain("localhost".to_string()))
.credentials(Credentials::new(send_from.to_string(), passwd.to_string()))
.smtp_utf8(true)
.authentication_mechanism(Mechanism::Plain)
.connection_reuse(ConnectionReuseParameters::ReuseUnlimited).build();
let result = mailer.send(&email);
if !result.is_ok() {
println!("send_email() get error: {:#?}", result);
}
mailer.close();
}
网友评论