aliyun_openapi/
dm.rs

1use crate::auth::sign_url;
2
3const API_VERSION: &str = "2015-11-23";
4
5/// Simple Email
6#[derive(Debug, Default)]
7pub struct SimpleMail<'a> {
8    /// same as service account on DM console
9    sender: &'a str,
10    /// from alias, such as Customer Support, Admin
11    sender_alias: &'a str,
12    /// receiver email
13    receiver: &'a str,
14    /// email subject
15    subject: &'a str,
16    /// html body
17    html_body: &'a str,
18    /// text body
19    text_body: &'a str,
20}
21
22/// Direct Mail(DM)  https://cn.aliyun.com/product/directmail
23#[doc(alias = "mail")]
24pub struct DM<'a> {
25    /// endpoint, such as `dm.aliyuncs.com`
26    pub endpoint: &'a str,
27    /// global reqwest::Client
28    pub http_client: &'a reqwest::Client,
29}
30
31impl<'a> DM<'a> {
32    pub async fn send(&self, simple_mail: &SimpleMail<'_>) -> reqwest::Result<bool> {
33        let mut params: Vec<(&str, &str)> = Vec::new();
34        params.push(("AccountName", simple_mail.sender));
35        params.push(("FromAlias", simple_mail.sender_alias));
36        params.push(("AddressType", "1"));
37        params.push(("ReplyToAddress", "true"));
38        params.push(("Subject", simple_mail.subject));
39        params.push(("ToAddress", simple_mail.receiver));
40        params.push(("HtmlBody", simple_mail.html_body));
41        let url = sign_url("POST", self.endpoint, API_VERSION,
42                           "SingleSendMail", params.as_ref());
43        let resp = self.http_client
44            .post(&url)
45            .send().await?;
46        return resp.error_for_status().map(|response| response.status().is_success());
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use crate::dm::{SimpleMail, DM};
53
54    #[tokio::test]
55    async fn test_send() -> Result<(), Box<dyn std::error::Error>> {
56        let mail = SimpleMail {
57            sender: "support@microservices.club",
58            sender_alias: "MicroServicesClub",
59            subject: "this is hello",
60            receiver: "libing.chen@gmail.com",
61            html_body: "<p>This is hello!</p>",
62            text_body: "This is hello!",
63        };
64        let endpoint = "dm.aliyuncs.com";
65        let ref http_client = reqwest::Client::new();
66        let dm = DM { endpoint, http_client };
67        let result = dm.send(&mail).await?;
68        println!("{}", result);
69        Ok(())
70    }
71}