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