smtp_send 0.1.7

SMTP email sending library with built-in DKIM signing and MX lookup support. / 支持内置 DKIM 签名和 MX 记录查询的 SMTP 邮件发送库。
Documentation

English | 中文


smtp_send : Secure SMTP Email Sending with DKIM

smtp_send is a robust Rust library designed for sending emails via SMTP with built-in support for DKIM signing and automatic MX record lookups. It simplifies the process of sending authenticated emails, ensuring high deliverability and security.

Table of Contents

Introduction

Sending emails programmatically often involves complex configurations, especially when dealing with authentication standards like DKIM (DomainKeys Identified Mail) and finding the correct mail servers (MX records). smtp_send abstracts these complexities, providing a streamlined interface to send signed emails directly to recipient mail servers.

Features

  • Automatic DKIM Signing: Signs emails using RSA-SHA256 to ensure authenticity and integrity.
  • Smart MX Lookup: Automatically resolves MX records for recipient domains using DNS-over-HTTPS (DoH).
  • Recipient Grouping: Efficiently groups recipients by domain to minimize connections.
  • Failover Support: Tries multiple MX servers if the primary one fails.
  • Security Best Practices: Implements RFC 6376 recommendations, such as over-signing headers to prevent tampering.

Usage

Here is a basic example of how to use smtp_send to send an email.

use smtp_send::Send;
use mail_struct::Mail;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Load DKIM private key from file
    // In a real app, load this from a secure source
    let sk_bytes = std::fs::read("path/to/private.key")?; 

    // 2. Create sender using the new() method
    let sender = Send::new("default", &sk_bytes); // "default" is your DKIM selector

    // 3. Construct the Email
    let mail = Mail {
        sender: "sender@example.com".to_string(),
        rcpt_to: vec![
            // ... recipients ...
        ],
        // ... other mail fields ...
    };

    // 4. Send the Email
    // Returns a SendResult struct containing success count and error details
    let result = sender.send(&mail).await;

    println!("Successfully sent to {} recipients", result.success);

    if !result.error.dns_resolve_failed.is_empty() {
        println!("DNS resolution failed for domains: {:?}", result.error.dns_resolve_failed);
    }

    if !result.error.mx_is_empty.is_empty() {
        println!("No MX records found for domains: {:?}", result.error.mx_is_empty);
    }

    if !result.error.send_err_li.is_empty() {
        println!("Failed to send to recipients: {:?}", result.error.send_err_li);
    }

    Ok(())
}

Note: See @tests/main.rs for more comprehensive examples.

Design

The library follows a logical flow to ensure reliable delivery:

  1. Input: Takes a Mail object and DKIM configuration (Send struct).
  2. Grouping: Recipients are grouped by their domain (e.g., all @gmail.com users together).
  3. MX Resolution: For each domain, the library queries DNS (via DoH) to find the Mail Exchange (MX) records.
  4. Signing: The email is cryptographically signed using the provided Private Key and Selector.
  5. Transmission: The library connects to the target SMTP server (port 25) and delivers the signed message.
  6. Result: Returns a list of any recipients that failed to receive the message.

Technology Stack

  • Rust: The core language, chosen for safety and performance.
  • mail_send: Handles the low-level SMTP protocol interactions.
  • idoh: Performs DNS-over-HTTPS lookups for MX records.
  • sk_dkim: Manages DKIM secret keys and signing operations.
  • dashmap: Provides concurrent caching for MX records and signers.

Directory Structure

.
├── Cargo.toml      # Project configuration and dependencies
├── readme/         # Documentation files
│   ├── en.md       # English README
│   └── zh.md       # Chinese README
├── src/            # Source code
│   ├── dkim.rs     # DKIM signer implementation and caching
│   ├── send_error.rs # SendError struct and serialization helpers
│   └── lib.rs      # Main library entry point and logic
└── tests/          # Integration tests
    └── main.rs     # Usage examples and verification tests

API Reference

struct Send

The main configuration struct for sending emails.

  • selector: String: The DKIM selector (e.g., "default", "mail"). This tells the receiver where to find the public key in DNS.
  • sk: Sk: The Secret Key used for signing.

impl Send

fn new(selector: impl Into<String>, sk: impl AsRef<[u8]>) -> Self

Creates a new Send instance.

  • Parameters:
    • selector: The DKIM selector, can be any type that converts to String (e.g., &str or String).
    • sk: The DKIM private key bytes, can be any type implementing AsRef<[u8]> (e.g., &[u8], Vec<u8>, etc.).
  • Returns:
    • Send: A configured sender instance.

async fn send(&self, mail: &Mail) -> SendResult

Sends the provided email to all recipients.

  • Parameters:
    • mail: A reference to the Mail struct containing sender, recipients, and content.
  • Returns:
    • SendResult: A struct containing the results of the sending operation, including success count and any errors encountered.

struct SendResult

The result of a send operation.

  • success: usize: The number of recipients the email was successfully sent to.
  • error: SendError: A struct containing detailed error information.

struct SendError

Detailed error information for the send operation.

  • dns_resolve_failed: Vec<(String, idoh::Error)>: List of domains where DNS resolution failed.
  • mx_is_empty: Vec<String>: List of domains with no MX records.
  • send_err_li: Vec<(String, Vec<(String, mail_send::Error)>)>: List of recipients where sending failed, with specific errors per MX server attempted.

History

The Merger that Created DKIM

In the early 2000s, as email spam and phishing became rampant, two major tech giants independently worked on solutions. Yahoo! developed DomainKeys, focusing on verifying the DNS domain of a sender. Simultaneously, Cisco created Identified Internet Mail (IIM), which proposed a signature-based authentication standard.

Recognizing that a unified standard would be more effective, these two distinct approaches were merged in 2004. This collaboration birthed DKIM (DomainKeys Identified Mail). It combined the cryptographic integrity of IIM with the domain verification of DomainKeys. This unified specification eventually became an Internet Standard (RFC 6376) in 2011, becoming a cornerstone of modern email security alongside SPF and DMARC.


About

This project is an open-source component of js0.site ⋅ Refactoring the Internet Plan.

We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:


smtp_send : 支持 DKIM 签名的安全 SMTP 邮件发送工具

smtp_send 是一个强大的 Rust 库,专为通过 SMTP 发送邮件而设计,内置了 DKIM 签名支持和自动 MX 记录查询功能。它简化了发送认证邮件的流程,确保了高送达率和安全性。

目录

简介

通过程序发送邮件通常涉及复杂的配置,尤其是涉及到 DKIM(域名密钥识别邮件)等认证标准以及查找正确的邮件服务器(MX 记录)时。smtp_send 抽象了这些复杂性,提供了一个精简的接口,可以直接将带有签名的邮件发送到收件人的邮件服务器。

功能特性

  • 自动 DKIM 签名:使用 RSA-SHA256 对邮件进行签名,确保真实性和完整性。
  • 智能 MX 查询:使用 DNS-over-HTTPS (DoH) 自动解析收件人域名的 MX 记录。
  • 收件人分组:按域名高效分组收件人,以最小化连接数。
  • 故障转移支持:如果主 MX 服务器失败,自动尝试其他 MX 服务器。
  • 安全最佳实践:实现了 RFC 6376 建议,例如对头部进行过度签名以防止篡改。

使用演示

以下是如何使用 smtp_send 发送邮件的基本示例。

use smtp_send::Send;
use mail_struct::Mail;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. 从文件加载 DKIM 私钥
    // 在实际应用中,请从安全来源加载
    let sk_bytes = std::fs::read("path/to/private.key")?; 

    // 2. 使用 new() 方法创建发送器
    let sender = Send::new("default", &sk_bytes); // "default" 是你的 DKIM 选择器

    // 3. 构建邮件
    let mail = Mail {
        sender: "sender@example.com".to_string(),
        rcpt_to: vec![
            // ... 收件人列表 ...
        ],
        // ... 其他邮件字段 ...
    };

    // 4. 发送邮件
    // 返回 SendResult 结构体,包含成功数量和错误详情
    let result = sender.send(&mail).await;

    println!("成功发送给 {} 位收件人", result.success);

    if !result.error.dns_resolve_failed.is_empty() {
        println!("域名 DNS 解析失败: {:?}", result.error.dns_resolve_failed);
    }

    if !result.error.mx_is_empty.is_empty() {
        println!("未找到 MX 记录的域名: {:?}", result.error.mx_is_empty);
    }

    if !result.error.send_err_li.is_empty() {
        println!("发送失败的收件人: {:?}", result.error.send_err_li);
    }

    Ok(())
}

注意:更多详细示例请参考 @tests/main.rs。

设计思路

本库遵循逻辑流程以确保可靠的交付:

  1. 输入:接收 Mail 对象和 DKIM 配置(Send 结构体)。
  2. 分组:收件人按其域名分组(例如,所有 @gmail.com 用户分在一组)。
  3. MX 解析:对于每个域名,库通过 DNS (DoH) 查询邮件交换 (MX) 记录。
  4. 签名:使用提供的私钥和选择器对邮件进行加密签名。
  5. 传输:库连接到目标 SMTP 服务器(端口 25)并投递签名消息。
  6. 结果:返回任何未能接收消息的收件人列表。

技术堆栈

  • Rust:核心语言,因其安全性和性能而选择。
  • mail_send:处理底层 SMTP 协议交互。
  • idoh:执行 DNS-over-HTTPS 查询以获取 MX 记录。
  • sk_dkim:管理 DKIM 私钥和签名操作。
  • dashmap:为 MX 记录和签名者提供并发缓存。

目录结构

.
├── Cargo.toml      # 项目配置和依赖
├── readme/         # 文档文件
│   ├── en.md       # 英文 README
│   └── zh.md       # 中文 README
├── src/            # 源代码
│   ├── dkim.rs     # DKIM 签名器实现和缓存
│   ├── send_error.rs # SendError 结构体和序列化辅助函数
│   └── lib.rs      # 主库入口点和逻辑
└── tests/          # 集成测试
    └── main.rs     # 使用示例和验证测试

API 参考

struct Send

用于发送邮件的主要配置结构体。

  • selector: String: DKIM 选择器(例如 "default", "mail")。这告诉接收方在 DNS 中哪里可以找到公钥。
  • sk: Sk: 用于签名的私钥。

impl Send

fn new(selector: impl Into<String>, sk: impl AsRef<[u8]>) -> Self

创建一个新的 Send 实例。

  • 参数:
    • selector: DKIM 选择器,可以是任何可转换为 String 的类型(如 &str 或 String)。
    • sk: DKIM 私钥字节,可以是任何实现 AsRef<[u8]> 的类型(如 &[u8]、Vec<u8> 等)。
  • 返回:
    • Send: 配置好的发送器实例。

async fn send(&self, mail: &Mail) -> SendResult

将提供的邮件发送给所有收件人。

  • 参数:
    • mail: 包含发件人、收件人和内容的 Mail 结构体的引用。
  • 返回:
    • SendResult: 包含发送操作结果的结构体,包括成功数量和遇到的任何错误。

struct SendResult

发送操作的结果。

  • success: usize: 邮件成功发送到的收件人数量。
  • error: SendError: 包含详细错误信息的结构体。

struct SendError

发送操作的详细错误信息。

  • dns_resolve_failed: Vec<(String, idoh::Error)>: DNS 解析失败的域名列表。
  • mx_is_empty: Vec<String>: 没有 MX 记录的域名列表。
  • send_err_li: Vec<(String, Vec<(String, mail_send::Error)>)>: 发送失败的收件人列表,包含每个尝试过的 MX 服务器的具体错误。

历史故事

DKIM 诞生的融合

在 2000 年代初,随着垃圾邮件和网络钓鱼变得猖獗,两大科技巨头分别致力于解决方案。Yahoo! 开发了 DomainKeys,专注于验证发件人的 DNS 域名。与此同时,Cisco 创建了 Identified Internet Mail (IIM),提出了一种基于签名的认证标准。

认识到统一的标准将更有效,这两种不同的方法在 2004 年合并。这次合作诞生了 DKIM (DomainKeys Identified Mail)。它结合了 IIM 的加密完整性和 DomainKeys 的域验证。这一统一规范最终在 2011 年成为互联网标准 (RFC 6376),与 SPF 和 DMARC 一起成为现代电子邮件安全的基石。


关于

本项目为 js0.site ⋅ 重构互联网计划 的开源组件。

我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注: