Lines of
src/mail.rs
from check-in 6ce625a569
that are changed by the sequence of edits moving toward
check-in 700254f838:
1: use crate::{
2: Cursor,
3: telegram::TelegramTransport,
4: utils::{
5: Attachment,
6: RE_DOMAIN,
7: validate,
8: },
9: };
10:
11: use std::{
12: collections::{
13: HashMap,
14: HashSet,
15: },
16: io::Error,
17: sync::Arc,
18: };
19:
20: use async_compat::Compat;
21: use mailin_embedded::{
22: Response,
23: response::{
24: INTERNAL_ERROR,
25: INVALID_CREDENTIALS,
26: NO_MAILBOX,
27: OK
28: },
29: };
30: use regex::{
31: Regex,
32: escape,
33: };
34: use stacked_errors::{
35: Result,
36: StackableErr,
37: bail,
38: };
39: use tgbot::types::ChatPeerId;
40:
41: /// `SomeHeaders` object to store data through SMTP session
42: #[derive(Clone, Debug)]
43: struct SomeHeaders {
44: from: String,
45: to: Vec<String>,
46: }
47:
48: /// `MailServer` Central object with TG api and configuration
49: #[derive(Clone, Debug)]
50: pub struct MailServer {
51: data: Vec<u8>,
52: headers: Option<SomeHeaders>,
53: relay: bool,
54: tg: Arc<TelegramTransport>,
55: fields: HashSet<String>,
56: address: Regex,
57: }
58:
59: impl MailServer {
60: /// Initialize API and read configuration
61: pub fn new(settings: config::Config) -> Result<MailServer> {
62: let api_key = settings.get_string("api_key")
63: .context("[smtp2tg.toml] missing \"api_key\" parameter.\n")?;
64: let mut recipients = HashMap::new();
65: for (name, value) in settings.get_table("recipients")
66: .expect("[smtp2tg.toml] missing table \"recipients\".\n")
67: {
68: let value = value.into_int()
69: .context("[smtp2tg.toml] \"recipient\" table values should be integers.\n")?;
70: recipients.insert(name, value);
71: }
72:
73: let tg = Arc::new(TelegramTransport::new(api_key, recipients, &settings)?);
74: let fields = HashSet::<String>::from_iter(settings.get_array("fields")
75: .expect("[smtp2tg.toml] \"fields\" should be an array")
76: .iter().map(|x| x.clone().into_string().expect("should be strings")));
77: let mut domains: HashSet<String> = HashSet::new();
78: let extra_domains = settings.get_array("domains").stack()?;
79: for domain in extra_domains {
80: let domain = domain.to_string().to_lowercase();
81: if RE_DOMAIN.is_match(&domain) {
82: domains.insert(domain);
83: } else {
84: panic!("[smtp2tg.toml] can't check of domains in \"domains\": {domain}");
85: }
86: }
87: let domains = domains.into_iter().map(|s| escape(&s))
88: .collect::<Vec<String>>().join("|");
89: let address = Regex::new(&format!("^(?P<user>[a-z0-9][-a-z0-9])(@({domains}))$")).stack()?;
90: let relay = match settings.get_string("unknown")
91: .context("[smtp2tg.toml] can't get \"unknown\" policy.\n")?.as_str()
92: {
93: "relay" => true,
94: "deny" => false,
95: _ => {
96: bail!("[smtp2tg.toml] \"unknown\" should be either \"relay\" or \"deny\".\n");
97: },
98: };
99:
100: Ok(MailServer {
101: data: vec!(),
102: headers: None,
103: relay,
104: tg,
105: fields,
106: address,
107: })
108: }
109:
110: /// Returns id for provided email address
111: fn get_id (&self, name: &str) -> Result<&ChatPeerId> {
112: // here we need to store String locally to borrow it after
113: let mut link = name;
114: let name: String;
115: if let Some(caps) = self.address.captures(link) {
116: name = caps["name"].to_string();
117: link = &name;
118: }
119: match self.tg.get(link) {
120: Ok(addr) => Ok(addr),
121: Err(_) => Ok(&self.tg.default),
122: }
123: }
124:
125: /// Attempt to deliver one message
126: async fn relay_mail (&self) -> Result<()> {
127: if let Some(headers) = &self.headers {
128: let mail = mail_parser::MessageParser::new().parse(&self.data)
129: .context("Failed to parse mail.")?;
130:
131: // Adding all known addresses to recipient list, for anyone else adding default
132: // Also if list is empty also adding default
133: let mut rcpt: HashSet<&ChatPeerId> = HashSet::new();
134: if headers.to.is_empty() && !self.relay {
135: bail!("Relaying is disabled, and there's no destination address");
136: }
137: for item in &headers.to {
138: rcpt.insert(self.get_id(item)?);
139: };
140: if rcpt.is_empty() {
141: self.tg.debug("No recipient or envelope address.").await?;
142: rcpt.insert(&self.tg.default);
143: };
144:
145: // preparing message header
146: let mut reply: Vec<String> = vec!["<blockquote expandable>".into()];
147: if self.fields.contains("subject") {
148: if let Some(subject) = mail.subject() {
149: reply.push(format!("<u><i>Subject:</i></u> <code>{}</code>", validate(subject).stack()?));
150: } else if let Some(thread) = mail.thread_name() {
151: reply.push(format!("<u><i>Thread:</i></u> <code>{}</code>", validate(thread).stack()?));
152: }
153: }
154: // do we need to replace spaces here?
155: if self.fields.contains("from") {
156: reply.push(format!("<u><i>From:</i></u> <code>{}</code>", validate(&headers.from).stack()?));
157: }
158: if self.fields.contains("date")
159: && let Some(date) = mail.date()
160: {
161: reply.push(format!("<u><i>Date:</i></u> <code>{date}</code>"));
162: }
163: reply.push("</blockquote><pre>".into());
164: let reply = reply.join("\n");
165:
166: let html_parts = mail.html_body_count();
167: let text_parts = mail.text_body_count();
168: let attachments = mail.attachment_count();
169: if html_parts != text_parts {
170: self.tg.debug(&format!("Hm, we have {html_parts} HTML parts and {text_parts} text parts.")).await?;
171: }
172: //let mut html_num = 0;
173: let mut text_num = 0;
174: let mut file_num = 0;
175: // let's display first html or text part as body
176: let mut body: String = "".into();
177: /*
178: * actually I don't wanna parse that html stuff
179: if html_parts > 0 {
180: let text = mail.body_html(0).stack()?;
181: if text.len() < 4096 - header_size {
182: body = text;
183: html_num = 1;
184: }
185: };
186: */
187: if body.is_empty() && text_parts > 0 {
188: let text = mail.body_text(0)
189: .context("Failed to extract text from message")?
190: .replace("\r\n", "\n");
191: // 6:
192: // - (headers)
193: // - (mail text)
194: // - 6: </pre>
195: if text.len() < 4096 - ( reply.len() + 6 ) {
196: body = text;
197: text_num = 1;
198: }
199: };
200: let msg = format!("{}{}</pre>", reply, validate(&body).stack()?);
201:
202: // and let's collect all other attachment parts
203: let mut files_to_send = vec![];
204: /*
205: * let's just skip html parts for now, they just duplicate text?
206: while html_num < html_parts {
207: files_to_send.push(mail.html_part(html_num).stack()?);
208: html_num += 1;
209: }
210: */
211: while text_num < text_parts {
212: files_to_send.push(mail.text_part(text_num.try_into().stack()?)
213: .context("Failed to get text part from message.")?);
214: text_num += 1;
215: }
216: while file_num < attachments {
217: files_to_send.push(mail.attachment(file_num.try_into().stack()?)
218: .context("Failed to get file part from message.")?);
219: file_num += 1;
220: }
221:
222: for chat in rcpt {
223: if !files_to_send.is_empty() {
224: let mut files = vec![];
225: // let mut first_one = true;
226: for chunk in &files_to_send {
227: let data: Vec<u8> = chunk.contents().to_vec();
228: let mut filename: Option<String> = None;
229: for header in chunk.headers() {
230: if header.name() == "Content-Type" {
231: match header.value() {
232: mail_parser::HeaderValue::ContentType(contenttype) => {
233: if let Some(fname) = contenttype.attribute("name") {
234: filename = Some(fname.to_owned());
235: }
236: },
237: _ => {
238: self.tg.debug("Attachment has bad ContentType header.").await?;
239: },
240: };
241: };
242: };
243: let filename = if let Some(fname) = filename {
244: fname
245: } else {
246: "Attachment.txt".into()
247: };
248: files.push(Attachment {
249: data: Cursor::new(data),
250: name: filename,
251: });
252: }
253: self.tg.sendgroup(chat, files, &msg).await?;
254: } else {
255: self.tg.send(chat, &msg).await?;
256: }
257: }
258: } else {
259: bail!("Required headers were not found.");
260: }
261: Ok(())
262: }
263: }
264:
265: impl mailin_embedded::Handler for MailServer {
266: /// Just deny login auth
267: fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
268: INVALID_CREDENTIALS
269: }
270:
271: /// Just deny plain auth
272: fn auth_plain (&mut self, _authorization_id: &str, _authentication_id: &str, _password: &str) -> Response {
273: INVALID_CREDENTIALS
274: }
275:
276: /// Verify whether address is deliverable
277: fn rcpt (&mut self, to: &str) -> Response {
278: if self.relay {
279: OK
280: } else {
281: match self.get_id(to) {
282: Ok(_) => OK,
283: Err(_) => {
284: if self.relay {
285: OK
286: } else {
287: NO_MAILBOX
288: }
289: }
290: }
291: }
292: }
293:
294: /// Save headers we need
295: fn data_start (&mut self, _domain: &str, from: &str, _is8bit: bool, to: &[String]) -> Response {
296: self.headers = Some(SomeHeaders{
297: from: from.to_string(),
298: to: to.to_vec(),
299: });
300: OK
301: }
302:
303: /// Save chunk(?) of data
304: fn data (&mut self, buf: &[u8]) -> std::result::Result<(), Error> {
305: self.data.append(buf.to_vec().as_mut());
306: Ok(())
307: }
308:
309: /// Attempt to send email, return temporary error if that fails
310: fn data_end (&mut self) -> Response {
311: let mut result = OK;
312: smol::block_on(Compat::new(async {
313: // relay mail
314: if let Err(err) = self.relay_mail().await {
315: result = INTERNAL_ERROR;
316: // in case that fails - inform default recipient
6ce625a569 2026-01-12 317: if let Err(err) = self.tg.debug(&format!("Sending emails failed:\n{err:?}")).await {
318: // in case that also fails - write some logs and bail
319: eprintln!("{err:?}");
320: };
321: };
322: }));
323: // clear - just in case
324: self.data = vec![];
325: self.headers = None;
326: result
327: }
328: }