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