- 作者:老汪软件技巧
- 发表时间:2024-11-13 07:02
- 浏览量:
POP、IMAP、SMTP是什么
这里使用SMTP发送邮件,所以要开启SMTP,由于outlook需要付费,这里使用qq邮箱
生成授权码,这个授权码就是邮件发送者的密码
1、添加crate
lettre = "0.11"
2、创建邮件对象和邮件发送者
同步发送,会阻塞代码
use lettre::{
message::header::ContentType,
transport::smtp::authentication::Credentials,
Message,
SmtpTransport,
Transport,
};
async fn main() {
// 创建邮件对象
let email = Message::builder()
// 设置邮件的发件人地址
.from("xxxxxxx@qq.com".parse().unwrap())
// 设置邮件的回复地址
.reply_to("xxxxxx@qq.com".parse().unwrap())
// 设置邮件的收件人地址
.to("xxxxxx@gmail.com".parse().unwrap())
// 设置邮件的主题
.subject("锈化动力商城验证码")
// 设置邮件的内容类型为纯文本
.header(ContentType::TEXT_PLAIN)
// 设置邮件的正文内容
.body(String::from("验证码为:123456"))
.unwrap();
// 创建邮件发送者,第一个参数是邮件发送者账号,第二个参数是邮件发送者密码,这里使用授权码
let creds = Credentials::new("xxxx@qq.com".to_owned(), "password".to_owned());
// 使用ssl打开mail远程链接,填写发送邮件服务器地址,端口为465或587
let mailer = SmtpTransport::starttls_relay("smtp.qq.com")
.unwrap()
.credentials(creds)
.port(587)
.build();
// 发送邮件
match mailer.send(&email) {
Ok(_) => println!("Email sent successfully!"),
Err(e) => println!("Could not send email: {e:?}"),
}
}
异步发送,不会阻塞代码Cargo.toml配置
tokio = { version = "1", features = ["full"] }
lettre = { version = "0.11.7", features = ["tokio1-native-tls", "builder"] }
代码
use lettre::{
AsyncSmtpTransport, AsyncTransport, Message,
message::header::ContentType, Tokio1Executor, transport::smtp::authentication::Credentials,
};
#[tokio::main]
async fn main() {
// 创建邮件对象
let email = Message::builder()
// 设置邮件的发件人地址
.from("xxxxx@qq.com".parse().unwrap())
// 设置邮件的回复地址
.reply_to("xxxx@qq.com".parse().unwrap())
// 设置邮件的收件人地址
.to("xxxx@gmail.com".parse().unwrap())
// 设置邮件的主题
.subject("锈化动力商城验证码")
// 设置邮件的内容类型为纯文本
.header(ContentType::TEXT_PLAIN)
// 设置邮件的正文内容
.body(String::from("验证码为:123456"))
.unwrap();
// 创建邮件发送者,第一个参数是邮件发送者账号,第二个参数是邮件发送者密码,这里使用授权码
let creds = Credentials::new("xxxxx@qq.com".to_owned(), "password".to_owned());
// 使用ssl打开mail远程链接,填写发送邮件服务器地址,端口为465或587
let mailer: AsyncSmtpTransport = AsyncSmtpTransport::
::starttls_relay("smtp.qq.com")
.unwrap()
.credentials(creds)
.port(587)
.build();
match mailer.send(email).await {
Ok(_) => println!("Email sent successfully!"),
Err(e) => println!("Could not send email: {e:?}"),
}
}
效果
实际生产请将unwrap()替换为?传递错误或其他错误处理方式,使用邮件进行注册登陆时可以生成的验证码往redis里写一份,key设置为邮件名,设置过期时间为60s,注册登陆时与redis中的验证码比较即可