1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use serde_json;
use crate::errors::{SendgridError, SendgridResult};
macro_rules! add_field {
($method:ident << $field:ident: $ty:ty) => {
pub fn $method(mut self, data: $ty) -> Mail<'a> {
self.$field.push(data);
self
}
};
($method:ident = $field:ident: $ty:ty) => {
pub fn $method(mut self, data: $ty) -> Mail<'a> {
self.$field = data;
self
}
};
($method:ident <- $field:ident: $ty:ty) => {
pub fn $method(mut self, id: String, data: $ty) -> Mail<'a> {
self.$field.insert(id, data);
self
}
};
}
#[derive(Debug)]
pub struct Destination<'a> {
pub address: &'a str,
pub name: &'a str,
}
#[derive(Debug, Default)]
pub struct Mail<'a> {
pub to: Vec<Destination<'a>>,
pub cc: Vec<&'a str>,
pub bcc: Vec<&'a str>,
pub from: &'a str,
pub subject: &'a str,
pub html: &'a str,
pub text: &'a str,
pub from_name: &'a str,
pub reply_to: &'a str,
pub date: &'a str,
pub attachments: HashMap<String, String>,
pub content: HashMap<String, &'a str>,
pub headers: HashMap<String, &'a str>,
pub x_smtpapi: &'a str,
}
impl<'a> Mail<'a> {
pub fn new() -> Mail<'a> {
Mail::default()
}
add_field!(add_cc << cc: &'a str);
add_field!(add_to << to: Destination<'a>);
add_field!(add_from = from: &'a str);
add_field!(add_subject = subject: &'a str);
add_field!(add_html = html: &'a str);
add_field!(add_text = text: &'a str);
add_field!(add_bcc << bcc: &'a str);
add_field!(add_from_name = from_name: &'a str);
add_field!(add_reply_to = reply_to: &'a str);
add_field!(add_date = date: &'a str);
pub fn build(self) -> Mail<'a> {
self
}
pub fn add_attachment<P: AsRef<Path>>(mut self, path: P) -> SendgridResult<Mail<'a>> {
let mut file = File::open(&path)?;
let mut data = String::new();
file.read_to_string(&mut data)?;
if let Some(name) = path.as_ref().to_str() {
self.attachments.insert(String::from(name), data);
} else {
return Err(SendgridError::InvalidFilename);
}
Ok(self)
}
add_field!(add_content <- content: &'a str);
add_field!(add_header <- headers: &'a str);
pub(crate) fn make_header_string(&mut self) -> SendgridResult<String> {
let string = serde_json::to_string(&self.headers)?;
Ok(string)
}
add_field!(add_x_smtpapi = x_smtpapi: &'a str);
}