Diff
Logged in as anonymous

Differences From Artifact [e3d881308d]:

To Artifact [152822e4ec]:


127
128
129
130
131
132
133
134

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

151
152
153
154
155
156
157
158
159
127
128
129
130
131
132
133

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

150


151
152
153
154
155
156
157







-
+















-
+
-
-







					_ => {
						eprintln!("[smtp2tg.toml] \"unknown\" should be either \"relay\" or \"deny\".\n");
						panic!("bad setting");
					},
				}
			},
			Err(err) => {
				eprintln!("[smtp2tg.toml] can't get \"unknown\":\n {}\n", err);
				eprintln!("[smtp2tg.toml] can't get \"unknown\":\n {err:?}\n");
				panic!("bad setting");
			},
		};

		TelegramTransport {
			data: vec!(),
			headers: None,
			recipients,
			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>
	async fn debug (&self, msg: &str) -> 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?)
171
172
173
174
175
176
177
178

179
180
181
182
183
184
185
169
170
171
172
173
174
175

176
177
178
179
180
181
182
183







-
+







			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?;
						self.debug(&format!("Recipient [{item}] not found.")).await?;
						rcpt.insert(self.recipients.get("_")
							.ok_or(MyError::NoDefault)?)
					}
				};
			};
			if rcpt.is_empty() {
				self.debug("No recipient or envelope address.").await?;
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
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







-
+



-
+









-
+







				} 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[..])));
				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));
					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?;
				self.debug(&format!("Hm, we have {html_parts} HTML parts and {text_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();
			/*
366
367
368
369
370
371
372
373

374
375

376
377
378
379
380
381
382
364
365
366
367
368
369
370

371
372

373
374
375
376
377
378
379
380







-
+

-
+







	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 {
				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);
					eprintln!("{err:?}");
				};
			};
		});
		// clear - just in case
		self.data = vec![];
		self.headers = None;
		result
391
392
393
394
395
396
397
398

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413

414
415
416
417
418
419
420


421
422
423
424
425
426
427
428
429
430
431
432
433


434
435
436
437
438
439
440
441
442
443
444
445
446
447
389
390
391
392
393
394
395

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

411
412
413
414
415
416


417
418

419
420
421
422
423
424
425
426
427
428


429
430

431
432
433
434
435
436
437
438
439
440
441
442
443







-
+














-
+





-
-
+
+
-










-
-
+
+
-













		.option("config", "c", OptValueType::Required)
		.option("config", "config", OptValueType::Required)
		.flag(OptFlags::OptionsEverywhere);
	let mut args = std::env::args();
	args.next();
	let parsed = specs.getopt(args);
	for u in &parsed.unknown {
		println!("Unknown option: {}", u);
		println!("Unknown option: {u}");
	}
	if !(parsed.unknown.is_empty()) || parsed.options_first("help").is_some() {
		println!("SMTP2TG v{}, (C) 2024 - 2025\n\n\
			\t-h|--help\tDisplay this help\n\
			\t-c|-config …\tSet configuration file location.",
			env!("CARGO_PKG_VERSION"));
		return Ok(());
	};
	let config_file = Path::new(if let Some(path) = parsed.options_value_last("config") {
		&path[..]
	} else {
		"smtp2tg.toml"
	});
	if !config_file.exists() {
		eprintln!("Error: can't read configuration from {:?}", config_file);
		eprintln!("Error: can't read configuration from {config_file:?}");
		std::process::exit(1);
	};
	{
		let meta = metadata(config_file).await?;
		if (!0o100600 & meta.permissions().mode()) > 0 {
			eprintln!("Error: other users can read or write config file {:?}\n\
				File permissions: {:o}",
			eprintln!("Error: other users can read or write config file {config_file:?}\n\
				File permissions: {:o}", meta.permissions().mode());
				config_file, meta.permissions().mode());
			std::process::exit(1);
		}
	}
	let settings: config::Config = config::Config::builder()
		.set_default("fields", vec!["date", "from", "subject"]).unwrap()
		.set_default("hostname", "smtp.2.tg").unwrap()
		.set_default("listen_on", "0.0.0.0:1025").unwrap()
		.set_default("unknown", "relay").unwrap()
		.add_source(config::File::from(config_file))
		.build()
		.expect(&format!("[{:?}] there was an error reading config\n\
			\tplease consult \"smtp2tg.toml.example\" for details",
		.unwrap_or_else(|_| panic!("[{config_file:?}] there was an error reading config\n\
			\tplease consult \"smtp2tg.toml.example\" for details"));
			config_file)[..]);

	let listen_on = settings.get_string("listen_on")?;
	let server_name = settings.get_string("hostname")?;
	let core = TelegramTransport::new(settings);
	let mut server = mailin_embedded::Server::new(core);

	server.with_name(server_name)
		.with_ssl(mailin_embedded::SslConfig::None).unwrap()
		.with_addr(listen_on).unwrap();
	server.serve().unwrap();

	Ok(())
}