Lines of
src/main.rs
from check-in 28fde40f7a
that are changed by the sequence of edits moving toward
check-in 3d13e7f81d:
1: //! Simple SMTP-to-Telegram gateway. Can parse email and send them as telegram
2: //! messages to specified chats, generally you specify which email address is
3: //! available in configuration, everything else is sent to default address.
4:
5: use anyhow::{
6: anyhow,
7: bail,
8: Result,
9: };
10: use async_std::{
11: io::Error,
12: task,
13: };
14: use mailin_embedded::{
15: Response,
16: response::*,
17: };
18: use teloxide::{
19: Bot,
20: prelude::{
21: Requester,
22: RequesterExt,
23: },
24: types::{
25: ChatId,
26: InputMedia,
27: Message,
28: ParseMode::MarkdownV2,
29: },
30: };
31:
32: use std::{
33: borrow::Cow,
34: collections::{
35: HashMap,
36: HashSet,
37: },
38: vec::Vec,
39: };
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: /// `TelegramTransport` Central object with TG api and configuration
49: #[derive(Clone)]
50: struct TelegramTransport {
51: data: Vec<u8>,
52: headers: Option<SomeHeaders>,
53: recipients: HashMap<String, ChatId>,
54: relay: bool,
55: tg: teloxide::adaptors::DefaultParseMode<teloxide::adaptors::Throttle<Bot>>,
56: fields: HashSet<String>,
57: }
58:
59: impl TelegramTransport {
60: /// Initialize API and read configuration
61: fn new(settings: config::Config) -> TelegramTransport {
62: let tg = Bot::new(settings.get_string("api_key")
63: .expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"))
64: .throttle(teloxide::adaptors::throttle::Limits::default())
65: .parse_mode(MarkdownV2);
66: let recipients: HashMap<String, ChatId> = settings.get_table("recipients")
67: .expect("[smtp2tg.toml] missing table \"recipients\".\n")
68: .into_iter().map(|(a, b)| (a, ChatId (b.into_int()
69: .expect("[smtp2tg.toml] \"recipient\" table values should be integers.\n")
70: ))).collect();
71: if !recipients.contains_key("_") {
72: eprintln!("[smtp2tg.toml] \"recipient\" table misses \"default_recipient\".\n");
73: panic!("no default recipient");
74: }
75: let fields = HashSet::<String>::from_iter(settings.get_array("fields")
76: .expect("[smtp2tg.toml] \"fields\" should be an array")
77: .iter().map(|x| x.clone().into_string().expect("should be strings")));
78: let value = settings.get_string("unknown");
79: let relay = match value {
80: Ok(value) => {
81: match value.as_str() {
82: "relay" => true,
83: "deny" => false,
84: _ => {
85: eprintln!("[smtp2tg.toml] \"unknown\" should be either \"relay\" or \"deny\".\n");
86: panic!("bad setting");
87: },
88: }
89: },
90: Err(err) => {
91: eprintln!("[smtp2tg.toml] can't get \"unknown\":\n {}\n", err);
92: panic!("bad setting");
93: },
94: };
95:
96: TelegramTransport {
97: data: vec!(),
98: headers: None,
99: recipients,
100: relay,
101: tg,
102: fields,
103: }
104: }
105:
106: /// Send message to default user, used for debug/log/info purposes
107: async fn debug<'b, S>(&self, msg: S) -> Result<Message>
108: where S: Into<String> {
109: Ok(self.tg.send_message(*self.recipients.get("_").unwrap(), msg).await?)
110: }
111:
112: /// Send message to specified user
113: async fn send<'b, S>(&self, to: &ChatId, msg: S) -> Result<Message>
114: where S: Into<String> {
115: Ok(self.tg.send_message(*to, msg).await?)
116: }
117:
118: /// Attempt to deliver one message
119: async fn relay_mail (&self) -> Result<()> {
120: if let Some(headers) = &self.headers {
121: let mail = mail_parser::MessageParser::new().parse(&self.data)
122: .ok_or(anyhow!("Failed to parse mail"))?;
123:
124: // Adding all known addresses to recipient list, for anyone else adding default
125: // Also if list is empty also adding default
126: let mut rcpt: HashSet<&ChatId> = HashSet::new();
127: if headers.to.is_empty() {
128: bail!("No recipient addresses.");
129: }
130: for item in &headers.to {
131: match self.recipients.get(item) {
132: Some(addr) => rcpt.insert(addr),
133: None => {
134: self.debug(format!("Recipient [{}] not found\\.", &item)).await?;
135: rcpt.insert(self.recipients.get("_")
136: .ok_or(anyhow!("Missing default address in recipient table\\."))?)
137: }
138: };
139: };
140: if rcpt.is_empty() {
141: self.debug("No recipient or envelope address\\.").await?;
142: rcpt.insert(self.recipients.get("_")
143: .ok_or(anyhow!("Missing default address in recipient table."))?);
144: };
145:
146: // prepating message header
147: let mut reply: Vec<Cow<'_, str>> = vec![];
148: if self.fields.contains("subject") {
149: if let Some(subject) = mail.subject() {
28fde40f7a 2024-12-27 150: reply.push(format!("**Subject:** `{}`", subject).into());
151: } else if let Some(thread) = mail.thread_name() {
28fde40f7a 2024-12-27 152: reply.push(format!("**Thread:** `{}`", thread).into());
153: }
154: }
155: if self.fields.contains("from") {
28fde40f7a 2024-12-27 156: reply.push(format!("**From:** `{}`", headers.from).into());
157: }
158: if self.fields.contains("date") {
159: if let Some(date) = mail.date() {
28fde40f7a 2024-12-27 160: reply.push(format!("**Date:** `{}`", date).into());
161: }
162: }
28fde40f7a 2024-12-27 163: reply.push("".into());
28fde40f7a 2024-12-27 164: let header_size = reply.join("\n").len() + 1;
165:
166: let html_parts = mail.html_body_count();
167: let text_parts = mail.text_body_count();
168: let attachments = mail.attachment_count();
169: if html_parts != text_parts {
170: self.debug(format!("Hm, we have {} HTML parts and {} text parts\\.", html_parts, text_parts)).await?;
171: }
172: //let mut html_num = 0;
173: let mut text_num = 0;
174: let mut file_num = 0;
175: // let's display first html or text part as body
176: let mut body = "".into();
177: /*
178: * actually I don't wanna parse that html stuff
179: if html_parts > 0 {
180: let text = mail.body_html(0).unwrap();
181: if text.len() < 4096 - header_size {
182: body = text;
183: html_num = 1;
184: }
185: };
186: */
187: if body == "" && text_parts > 0 {
188: let text = mail.body_text(0)
189: .ok_or(anyhow!("Failed to extract text from message."))?;
190: if text.len() < 4096 - header_size {
191: body = text;
192: text_num = 1;
193: }
194: };
195: reply.push("```".into());
196: reply.extend(body.lines().map(|x| x.into()));
197: reply.push("```".into());
198:
199: // and let's collect all other attachment parts
200: let mut files_to_send = vec![];
201: /*
202: * let's just skip html parts for now, they just duplicate text?
203: while html_num < html_parts {
204: files_to_send.push(mail.html_part(html_num).unwrap());
205: html_num += 1;
206: }
207: */
208: while text_num < text_parts {
209: files_to_send.push(mail.text_part(text_num)
210: .ok_or(anyhow!("Failed to get text part from message"))?);
211: text_num += 1;
212: }
213: while file_num < attachments {
214: files_to_send.push(mail.attachment(file_num)
215: .ok_or(anyhow!("Failed to get file part from message"))?);
216: file_num += 1;
217: }
218:
219: let msg = reply.join("\n");
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 = chunk.contents();
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.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: let item = teloxide::types::InputMediaDocument::new(
247: teloxide::types::InputFile::memory(data.to_vec())
248: .file_name(filename));
249: let item = if first_one {
250: first_one = false;
251: item.caption(&msg).parse_mode(MarkdownV2)
252: } else {
253: item
254: };
255: files.push(InputMedia::Document(item));
256: }
257: self.sendgroup(chat, files).await?;
258: } else {
259: self.send(chat, &msg).await?;
260: }
261: }
262: } else {
263: bail!("No headers.");
264: }
265: Ok(())
266: }
267:
268: /// Send media to specified user
269: pub async fn sendgroup<M>(&self, to: &ChatId, media: M) -> Result<Vec<Message>>
270: where M: IntoIterator<Item = InputMedia> {
271: Ok(self.tg.send_media_group(*to, media).await?)
272: }
273: }
274:
275: impl mailin_embedded::Handler for TelegramTransport {
276: /// Just deny login auth
277: fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
278: INVALID_CREDENTIALS
279: }
280:
281: /// Just deny plain auth
282: fn auth_plain (&mut self, _authorization_id: &str, _authentication_id: &str, _password: &str) -> Response {
283: INVALID_CREDENTIALS
284: }
285:
286: /// Verify whether address is deliverable
287: fn rcpt (&mut self, to: &str) -> Response {
288: if self.relay {
289: OK
290: } else {
291: match self.recipients.get(to) {
292: Some(_) => OK,
293: None => {
294: if self.relay {
295: OK
296: } else {
297: NO_MAILBOX
298: }
299: }
300: }
301: }
302: }
303:
304: /// Save headers we need
305: fn data_start (&mut self, _domain: &str, from: &str, _is8bit: bool, to: &[String]) -> Response {
306: self.headers = Some(SomeHeaders{
307: from: from.to_string(),
308: to: to.to_vec(),
309: });
310: OK
311: }
312:
313: /// Save chunk(?) of data
314: fn data(&mut self, buf: &[u8]) -> Result<(), Error> {
315: self.data.append(buf.to_vec().as_mut());
316: Ok(())
317: }
318:
319: /// Attempt to send email, return temporary error if that fails
320: fn data_end(&mut self) -> Response {
321: let mut result = OK;
322: task::block_on(async {
323: // relay mail
324: if let Err(err) = self.relay_mail().await {
325: result = INTERNAL_ERROR;
326: // in case that fails - inform default recipient
327: if let Err(err) = self.debug(format!("Sending emails failed:\n{:?}", err)).await {
328: // in case that also fails - write some logs and bail
329: eprintln!("Failed to contact Telegram:\n{:?}", err);
330: };
331: };
332: });
333: // clear - just in case
334: self.data = vec![];
335: self.headers = None;
336: result
337: }
338: }
339:
340: #[async_std::main]
341: async fn main() -> Result<()> {
342: let settings: config::Config = config::Config::builder()
343: .set_default("fields", vec!["date", "from", "subject"]).unwrap()
344: .set_default("hostname", "smtp.2.tg").unwrap()
345: .set_default("listen_on", "0.0.0.0:1025").unwrap()
346: .set_default("unknown", "relay").unwrap()
347: .add_source(config::File::with_name("smtp2tg.toml"))
348: .build()
349: .expect("[smtp2tg.toml] there was an error reading config\n\
350: \tplease consult \"smtp2tg.toml.example\" for details");
351:
352: let listen_on = settings.get_string("listen_on")?;
353: let server_name = settings.get_string("hostname")?;
354: let core = TelegramTransport::new(settings);
355: let mut server = mailin_embedded::Server::new(core);
356:
357: server.with_name(server_name)
358: .with_ssl(mailin_embedded::SslConfig::None).unwrap()
359: .with_addr(listen_on).unwrap();
360: server.serve().unwrap();
361:
362: Ok(())
363: }