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