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