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