Overview
Comment: | fix markdown errors, message passing, errors produced |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | trunk | v0.3.5 |
Files: | files | file ages | folders |
SHA3-256: |
65b2967a923f4b2e3dec9071c3bd6b4a |
User & Date: | arcade on 2025-01-25 06:21:24.025 |
Other Links: | manifest | tags |
Context
2025-02-04
| ||
07:30 | bump crates (openssl security issue) check-in: d4d634cfe7 user: arcade tags: trunk, v0.3.6 | |
2025-01-25
| ||
06:21 | fix markdown errors, message passing, errors produced check-in: 65b2967a92 user: arcade tags: trunk, v0.3.5 | |
2025-01-23
| ||
12:20 | Make buildable on older Rust versions, check that config file is only readable by owner check-in: cfe321bd6f user: arcade tags: trunk, v0.3.4 | |
Changes
Modified Cargo.lock
from [77073657ea]
to [dde5d25a9f].
︙ | ︙ | |||
523 524 525 526 527 528 529 | [[package]] name = "errno" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", | | | 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | [[package]] name = "errno" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", "windows-sys 0.59.0", ] [[package]] name = "event-listener" version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" |
︙ | ︙ | |||
1120 1121 1122 1123 1124 1125 1126 | [[package]] name = "libloading" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", | | | 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 | [[package]] name = "libloading" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", "windows-targets 0.52.6", ] [[package]] name = "linux-raw-sys" version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" |
︙ | ︙ | |||
1596 1597 1598 1599 1600 1601 1602 | source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" dependencies = [ "bitflags 2.8.0", "errno", "libc", "linux-raw-sys", | | | 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 | source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" dependencies = [ "bitflags 2.8.0", "errno", "libc", "linux-raw-sys", "windows-sys 0.59.0", ] [[package]] name = "rustls" version = "0.21.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" |
︙ | ︙ | |||
1851 1852 1853 1854 1855 1856 1857 | name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smtp2tg" | | > > > | 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 | name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smtp2tg" version = "0.3.5" dependencies = [ "anyhow", "async-std", "config", "just-getopt", "lazy_static", "mail-parser", "mailin-embedded", "regex", "teloxide", "thiserror 2.0.11", ] [[package]] name = "socket2" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" |
︙ | ︙ | |||
1986 1987 1988 1989 1990 1991 1992 | "futures", "log", "mime", "pin-project", "serde", "serde_json", "teloxide-core", | | | 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 | "futures", "log", "mime", "pin-project", "serde", "serde_json", "teloxide-core", "thiserror 1.0.69", "tokio", "tokio-stream", "tokio-util", "url", ] [[package]] |
︙ | ︙ | |||
2016 2017 2018 2019 2020 2021 2022 | "rc-box", "reqwest", "serde", "serde_json", "serde_with", "take_mut", "takecell", | | | | > > > > > > > > > > > > > > > > > > > > | 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 | "rc-box", "reqwest", "serde", "serde_json", "serde_with", "take_mut", "takecell", "thiserror 1.0.69", "tokio", "tokio-util", "url", "uuid", "vecrem", ] [[package]] name = "tempfile" version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" dependencies = [ "cfg-if", "fastrand", "getrandom", "once_cell", "rustix", "windows-sys 0.59.0", ] [[package]] name = "ternop" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d4ae32d0a4605a89c28534371b056919c12e7a070ee07505af75130ff030111" [[package]] name = "thiserror" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl 1.0.69", ] [[package]] name = "thiserror" version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" dependencies = [ "thiserror-impl 2.0.11", ] [[package]] name = "thiserror-impl" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", "syn 2.0.96", ] [[package]] name = "thiserror-impl" version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" dependencies = [ "proc-macro2", "quote", "syn 2.0.96", ] [[package]] name = "tinystr" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" dependencies = [ |
︙ | ︙ |
Modified Cargo.toml
from [e91521473b]
to [1d247a684d].
1 2 | [package] name = "smtp2tg" | | > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | [package] name = "smtp2tg" version = "0.3.5" authors = [ "arcade" ] edition = "2021" [dependencies] anyhow = "1.0.86" async-std = { version = "1.12.0", features = [ "attributes", "tokio1" ] } config = { version = "=0.14.0", default-features = false, features = [ "toml" ] } # Rust 1.75 just-getopt = "1.2.0" lazy_static = "1.5.0" regex = "1.11.1" teloxide = { version = "0.13", features = [ "rustls", "throttle" ] } thiserror = "2.0.11" mail-parser = { version = "0.9.3", features = ["serde", "serde_support"] } mailin-embedded = "^0" [profile.release] lto = true codegen-units = 1 |
Modified src/main.rs
from [86c96bbf98]
to [e3d881308d].
1 2 3 4 | //! Simple SMTP-to-Telegram gateway. Can parse email and send them as telegram //! messages to specified chats, generally you specify which email address is //! available in configuration, everything else is sent to default address. | | < < < < > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | //! Simple SMTP-to-Telegram gateway. Can parse email and send them as telegram //! messages to specified chats, generally you specify which email address is //! available in configuration, everything else is sent to default address. use anyhow::Result; use async_std::{ fs::metadata, io::Error, task, }; use just_getopt::{ OptFlags, OptSpecs, OptValueType, }; use lazy_static::lazy_static; use mailin_embedded::{ Response, response::*, }; use regex::Regex; use teloxide::{ Bot, prelude::{ Requester, RequesterExt, }, types::{ ChatId, InputMedia, Message, ParseMode::MarkdownV2, }, }; use thiserror::Error; use std::{ borrow::Cow, collections::{ HashMap, HashSet, }, os::unix::fs::PermissionsExt, path::Path, vec::Vec, }; #[derive(Error, Debug)] pub enum MyError { #[error("Failed to parse mail")] BadMail, #[error("Missing default address in recipient table")] NoDefault, #[error("No headers found")] NoHeaders, #[error("No recipient addresses")] NoRecipient, #[error("Failed to extract text from message")] NoText, #[error(transparent)] RequestError(#[from] teloxide::RequestError), } /// `SomeHeaders` object to store data through SMTP session #[derive(Clone, Debug)] struct SomeHeaders { from: String, to: Vec<String>, } /// `TelegramTransport` Central object with TG api and configuration #[derive(Clone)] struct TelegramTransport { data: Vec<u8>, headers: Option<SomeHeaders>, recipients: HashMap<String, ChatId>, relay: bool, tg: teloxide::adaptors::DefaultParseMode<teloxide::adaptors::Throttle<Bot>>, fields: HashSet<String>, } lazy_static! { static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap(); } /// Encodes special HTML entities to prevent them interfering with Telegram HTML fn encode (text: &str) -> Cow<'_, str> { RE_SPECIAL.replace_all(text, "\\$1") } #[cfg(test)] mod tests { use crate::encode; #[test] fn check_regex () { let res = encode("-_*[]()~`>#+|{}.!"); assert_eq!(res, "\\-\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\|\\{\\}\\.\\!"); } } impl TelegramTransport { /// Initialize API and read configuration fn new(settings: config::Config) -> TelegramTransport { let tg = Bot::new(settings.get_string("api_key") .expect("[smtp2tg.toml] missing \"api_key\" parameter.\n")) .throttle(teloxide::adaptors::throttle::Limits::default()) |
︙ | ︙ | |||
108 109 110 111 112 113 114 | relay, tg, fields, } } /// Send message to default user, used for debug/log/info purposes | | | > | | | | | | | | | | | | | | | | | | | | | | | | | 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | relay, tg, fields, } } /// Send message to default user, used for debug/log/info purposes async fn debug <'a, S> (&self, msg: S) -> Result<Message, MyError> where S: Into<&'a str> { let msg = msg.into(); Ok(self.tg.send_message(*self.recipients.get("_").ok_or(MyError::NoDefault)?, encode(msg)).await?) } /// Send message to specified user async fn send <S> (&self, to: &ChatId, msg: S) -> Result<Message, MyError> where S: Into<String> { Ok(self.tg.send_message(*to, msg).await?) } /// Attempt to deliver one message async fn relay_mail (&self) -> Result<(), MyError> { if let Some(headers) = &self.headers { let mail = mail_parser::MessageParser::new().parse(&self.data) .ok_or(MyError::BadMail)?; // Adding all known addresses to recipient list, for anyone else adding default // Also if list is empty also adding default let mut rcpt: HashSet<&ChatId> = HashSet::new(); if headers.to.is_empty() { return Err(MyError::NoRecipient); } for item in &headers.to { match self.recipients.get(item) { Some(addr) => rcpt.insert(addr), None => { self.debug(&*format!("Recipient [{}] not found.", &item)).await?; rcpt.insert(self.recipients.get("_") .ok_or(MyError::NoDefault)?) } }; }; if rcpt.is_empty() { self.debug("No recipient or envelope address.").await?; rcpt.insert(self.recipients.get("_") .ok_or(MyError::NoDefault)?); }; // prepating message header let mut reply: Vec<String> = vec![]; if self.fields.contains("subject") { if let Some(subject) = mail.subject() { reply.push(format!("__*Subject:*__ `{}`", encode(subject))); } else if let Some(thread) = mail.thread_name() { reply.push(format!("__*Thread:*__ `{}`", encode(thread))); } } let mut short_headers: Vec<String> = vec![]; // do we need to replace spaces here? if self.fields.contains("from") { short_headers.push(format!("__*From:*__ `{}`", encode(&headers.from[..]))); } if self.fields.contains("date") { if let Some(date) = mail.date() { short_headers.push(format!("__*Date:*__ `{}`", date)); } } reply.push(short_headers.join(" ")); let header_size = reply.join(" ").len() + 1; let html_parts = mail.html_body_count(); let text_parts = mail.text_body_count(); let attachments = mail.attachment_count(); if html_parts != text_parts { self.debug(&*format!("Hm, we have {} HTML parts and {} text parts.", html_parts, text_parts)).await?; } //let mut html_num = 0; let mut text_num = 0; let mut file_num = 0; // let's display first html or text part as body let mut body = "".into(); /* * actually I don't wanna parse that html stuff if html_parts > 0 { let text = mail.body_html(0).unwrap(); if text.len() < 4096 - header_size { body = text; html_num = 1; } }; */ if body == "" && text_parts > 0 { let text = mail.body_text(0) .ok_or(MyError::NoText)?; if text.len() < 4096 - header_size { body = text; text_num = 1; } }; reply.push("```".into()); reply.extend(body.lines().map(|x| x.into())); reply.push("```".into()); // and let's collect all other attachment parts let mut files_to_send = vec![]; /* * let's just skip html parts for now, they just duplicate text? while html_num < html_parts { files_to_send.push(mail.html_part(html_num).unwrap()); html_num += 1; } */ while text_num < text_parts { files_to_send.push(mail.text_part(text_num) .ok_or(MyError::NoText)?); text_num += 1; } while file_num < attachments { files_to_send.push(mail.attachment(file_num) .ok_or(MyError::NoText)?); file_num += 1; } let msg = reply.join("\n"); for chat in rcpt { if !files_to_send.is_empty() { let mut files = vec![]; let mut first_one = true; for chunk in &files_to_send { let data = chunk.contents(); let mut filename: Option<String> = None; for header in chunk.headers() { if header.name() == "Content-Type" { match header.value() { mail_parser::HeaderValue::ContentType(contenttype) => { if let Some(fname) = contenttype.attribute("name") { filename = Some(fname.to_owned()); } }, _ => { self.debug("Attachment has bad ContentType header.").await?; }, }; }; }; let filename = if let Some(fname) = filename { fname } else { "Attachment.txt".into() }; let item = teloxide::types::InputMediaDocument::new( teloxide::types::InputFile::memory(data.to_vec()) .file_name(filename)); let item = if first_one { first_one = false; item.caption(&msg) } else { item }; files.push(InputMedia::Document(item)); } self.sendgroup(chat, files).await?; } else { self.send(chat, &msg).await?; } } } else { return Err(MyError::NoHeaders); } Ok(()) } /// Send media to specified user pub async fn sendgroup <M> (&self, to: &ChatId, media: M) -> Result<Vec<Message>, MyError> where M: IntoIterator<Item = InputMedia> { Ok(self.tg.send_media_group(*to, media).await?) } } impl mailin_embedded::Handler for TelegramTransport { /// Just deny login auth |
︙ | ︙ | |||
317 318 319 320 321 322 323 | from: from.to_string(), to: to.to_vec(), }); OK } /// Save chunk(?) of data | | | | | | | 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | from: from.to_string(), to: to.to_vec(), }); OK } /// Save chunk(?) of data fn data (&mut self, buf: &[u8]) -> Result<(), Error> { self.data.append(buf.to_vec().as_mut()); Ok(()) } /// Attempt to send email, return temporary error if that fails fn data_end (&mut self) -> Response { let mut result = OK; task::block_on(async { // relay mail if let Err(err) = self.relay_mail().await { result = INTERNAL_ERROR; // in case that fails - inform default recipient if let Err(err) = self.debug(&*format!("Sending emails failed:\n{}", err)).await { // in case that also fails - write some logs and bail eprintln!("{:?}", err); }; }; }); // clear - just in case self.data = vec![]; self.headers = None; result } } #[async_std::main] async fn main () -> Result<()> { let specs = OptSpecs::new() .option("help", "h", OptValueType::None) .option("help", "help", OptValueType::None) .option("config", "c", OptValueType::Required) .option("config", "config", OptValueType::Required) .flag(OptFlags::OptionsEverywhere); let mut args = std::env::args(); |
︙ | ︙ |