Diff
Logged in as anonymous

Differences From Artifact [7aeca7c38c]:

To Artifact [931424421b]:






1
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23




use anyhow::{
	anyhow,

	Result,
};
use async_std::task;
use samotop::{
	mail::{
		Builder,
		DebugService,
		MailDir,
		Name
	},
	smtp::{
		SmtpParser,
		Prudence,
	},
};
use teloxide::{
	Bot,
	prelude::{
		Requester,
		RequesterExt,
	},
>
>
>
>


>


|
<
|
<
<
<
|
|
|
|
|
<







1
2
3
4
5
6
7
8
9
10

11



12
13
14
15
16

17
18
19
20
21
22
23
//! 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::{
	anyhow,
	bail,
	Result,
};
use async_std::{

	io::Error,



	task,
};
use mailin_embedded::{
	Response,
	response::*,

};
use teloxide::{
	Bot,
	prelude::{
		Requester,
		RequesterExt,
	},
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343

use std::{
	borrow::Cow,
	collections::{
		HashMap,
		HashSet,
	},
	io::Read,
	os::unix::fs::{
		FileTypeExt,
		PermissionsExt,
	},
	path::{
		Path,
		PathBuf
	},
	time::Duration,
	vec::Vec,
};

fn address_into_iter<'a>(addr: &'a mail_parser::Address<'a, >) -> impl Iterator<Item = Cow<'a, str>> {
	addr.clone().into_list().into_iter().map(|a| a.address.unwrap())
}

async fn relay_mails(maildir: &Path, core: &TelegramTransport) -> Result<()> {
	let new_dir = maildir.join("new");

	std::fs::create_dir_all(&new_dir)?;

	let files = std::fs::read_dir(new_dir)?;
	for file in files {
		let file = file?;
		let mut buf: String = Default::default();
		std::fs::File::open(file.path())?.read_to_string(&mut buf)?;

		let mail = mail_parser::MessageParser::new().parse(&buf)
			.ok_or(anyhow!("Failed to parse mail `{:?}`.", file))?;

		// Fetching address lists from fields we know
		let mut to = HashSet::new();
		if let Some(addr) = mail.to() {
			let _ = address_into_iter(addr).map(|x| to.insert(x));
		};
		if let Some(addr) = mail.header("X-Samotop-To") {
			match addr {
				mail_parser::HeaderValue::Address(addr) => {
					let _ = address_into_iter(addr).map(|x| to.insert(x));
				},
				mail_parser::HeaderValue::Text(text) => {
					to.insert(text.clone());
				},
				_ => {}
			}
		};

		// 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();
		for item in to {
			let item = item.into_owned();
			match core.recipients.get(&item) {
				Some(addr) => rcpt.insert(addr),
				None => {
					core.debug(format!("Recipient [{}] not found.", &item)).await?;
					rcpt.insert(core.recipients.get("_")
						.ok_or(anyhow!("Missing default address in recipient table."))?)
				}
			};
		};
		if rcpt.is_empty() {
			core.debug("No recipient or envelope address.").await?;
			rcpt.insert(core.recipients.get("_")
				.ok_or(anyhow!("Missing default address in recipient table."))?);
		};

		// prepating message header
		let mut reply: Vec<Cow<'_, str>> = vec![];
		if let Some(subject) = mail.subject() {
			reply.push(format!("**Subject:** `{}`", subject).into());
		} else if let Some(thread) = mail.thread_name() {
			reply.push(format!("**Thread:** `{}`", thread).into());
		}
		if let Some(from) = mail.from() {
			reply.push(format!("**From:** `{:?}`", address_into_iter(from).collect::<Vec<_>>().join(", ")).into());
		}
		if let Some(sender) = mail.sender() {
			reply.push(format!("**Sender:** `{:?}`", address_into_iter(sender).collect::<Vec<_>>().join(", ")).into());
		}
		reply.push("".into());
		let header_size = reply.join("\n").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 {
			core.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(anyhow!("Failed to extract text from message."))?;
			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(anyhow!("Failed to get text part from message"))?);
			text_num += 1;
		}
		while file_num < attachments {
			files_to_send.push(mail.attachment(file_num)
				.ok_or(anyhow!("Failed to get file part from message"))?);
			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());
									}
								},
								_ => {
									core.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).parse_mode(MarkdownV2)
					} else {
						item
					};
					files.push(InputMedia::Document(item));
				}
				core.sendgroup(chat, files).await?;
			} else {
				core.send(chat, &msg).await?;
			}
		}

		std::fs::remove_file(file.path())?;
	}
	Ok(())
}

fn my_prudence() -> Prudence {
	Prudence::default().with_read_timeout(Duration::from_secs(60)).with_banner_delay(Duration::from_secs(1))
}

pub struct TelegramTransport {
	tg: teloxide::adaptors::DefaultParseMode<teloxide::adaptors::Throttle<Bot>>,
	recipients: HashMap<String, ChatId>,
}

impl TelegramTransport {

	pub 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())
			.parse_mode(MarkdownV2);
		let recipients: HashMap<String, ChatId> = settings.get_table("recipients")
			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
			.into_iter().map(|(a, b)| (a, ChatId (b.into_int()
				.expect("[smtp2tg.toml] \"recipient\" table values should be integers.\n")
				))).collect();
		if !recipients.contains_key("_") {
			eprintln!("[smtp2tg.toml] \"recipient\" table misses \"default_recipient\".\n");
			panic!("no default recipient");
		}


















		TelegramTransport {
			tg,

			recipients,


		}
	}


	pub async fn debug<'b, S>(&self, msg: S) -> Result<Message>
	where S: Into<String> {
		Ok(self.tg.send_message(*self.recipients.get("_").unwrap(), msg).await?)
	}


	pub async fn send<'b, S>(&self, to: &ChatId, msg: S) -> Result<Message>
	where S: Into<String> {
		Ok(self.tg.send_message(*to, msg).await?)
	}















































































































































	pub async fn sendgroup<M>(&self, to: &ChatId, media: M) -> Result<Vec<Message>>
	where M: IntoIterator<Item = InputMedia> {
		Ok(self.tg.send_media_group(*to, media).await?)
	}
}


































































#[async_std::main]
async fn main() {
	let settings: config::Config = config::Config::builder()



		.add_source(config::File::with_name("smtp2tg.toml"))
		.build()
		.expect("[smtp2tg.toml] there was an error reading config\n\
			\tplease consult \"smtp2tg.toml.example\" for details");

	let maildir: PathBuf = settings.get_string("maildir")
		.expect("[smtp2tg.toml] missing \"maildir\" parameter.\n").into();
	let listen_on = settings.get_string("listen_on")
		.expect("[smtp2tg.toml] missing \"listen_on\" parameter.\n");

	let core = TelegramTransport::new(settings);
	let sink = Builder + Name::new("smtp2tg") + DebugService +
		my_prudence() + MailDir::new(maildir.clone()).unwrap();

	task::spawn(async move {
		loop {
			// relay mails
			if let Err(err) = relay_mails(&maildir, &core).await {
				// in case that fails - inform default recipient
				if let Err(err) = core.debug(format!("Sending emails failed:\n{:?}", err)).await {
					// in case that also fails - write some logs and bail
					eprintln!("Failed to contact Telegram:\n{:?}", err);
				};
				task::sleep(Duration::from_secs(5 * 60)).await;
			};
			task::sleep(Duration::from_secs(5)).await;
		}
	});


	match listen_on.as_str() {
		"socket" => {
			let socket_path = "./smtp2tg.sock";
			match std::fs::symlink_metadata(socket_path) {
				Ok(metadata) => {
					if metadata.file_type().is_socket() {
						std::fs::remove_file(socket_path)
							.expect("[smtp2tg] failed to remove old socket.\n");
					} else {
						eprintln!("[smtp2tg] \"./smtp2tg.sock\" we wanted to use is actually not a socket.\n\
							[smtp2tg] please check the file and remove it manually.\n");
						panic!("socket path unavailable");
					}
				},
				Err(err) => {
					match err.kind() {
						std::io::ErrorKind::NotFound => {},
						_ => {
							eprintln!("{:?}", err);
							panic!("unhandled file type error");
						}
					};
				}
			};

			let sink = sink + samotop::smtp::Lmtp.with(SmtpParser);
			task::spawn(async move {
				// Postpone mode change on the socket. I can't actually change
				// other way, as UnixServer just grabs path, and blocks
				task::sleep(Duration::from_secs(1)).await;
				std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o777)).unwrap();
			});
			samotop::server::UnixServer::on(socket_path)
				.serve(sink.build()).await.unwrap();
		},
		_ => {
			let sink = sink + samotop::smtp::Esmtp.with(SmtpParser);
			samotop::server::TcpServer::on(listen_on)
				.serve(sink.build()).await.unwrap();
		},
	};
}







<
<
<
<
<
<
<
<
<
<



<
<
<
|
<
<
|
<
|
<
<
<
<
<
|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
<
<
|
<

<



>
|













>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>

|
>

>
>



>
|




>
|




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|

>
>
>





<
<
|
<
>

<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
>
|
<
<
<
<
|
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336


337

338
339


340












341

342
343
344




345






346











347
















348

use std::{
	borrow::Cow,
	collections::{
		HashMap,
		HashSet,
	},










	vec::Vec,
};




/// `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>>,

}

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())
			.parse_mode(MarkdownV2);
		let recipients: HashMap<String, ChatId> = settings.get_table("recipients")
			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
			.into_iter().map(|(a, b)| (a, ChatId (b.into_int()
				.expect("[smtp2tg.toml] \"recipient\" table values should be integers.\n")
				))).collect();
		if !recipients.contains_key("_") {
			eprintln!("[smtp2tg.toml] \"recipient\" table misses \"default_recipient\".\n");
			panic!("no default recipient");
		}
		let value = settings.get_string("unknown");
		let relay = match value {
			Ok(value) => {
				match value.as_str() {
					"relay" => true,
					"deny" => false,
					_ => {
						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);
				panic!("bad setting");
			},
		};

		TelegramTransport {
			data: vec!(),
			headers: None,
			recipients,
			relay,
			tg,
		}
	}

	/// Send message to default user, used for debug/log/info purposes
	async fn debug<'b, S>(&self, msg: S) -> Result<Message>
	where S: Into<String> {
		Ok(self.tg.send_message(*self.recipients.get("_").unwrap(), msg).await?)
	}

	/// Send message to specified user
	async fn send<'b, S>(&self, to: &ChatId, msg: S) -> Result<Message>
	where S: Into<String> {
		Ok(self.tg.send_message(*to, msg).await?)
	}

	/// Attempt to deliver one message
	async fn relay_mail (&self) -> Result<()> {
		if let Some(headers) = &self.headers {
			let mail = mail_parser::MessageParser::new().parse(&self.data)
				.ok_or(anyhow!("Failed to parse mail"))?;

			// 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() {
				bail!("No recipient addresses.");
			}
			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(anyhow!("Missing default address in recipient table."))?)
					}
				};
			};
			if rcpt.is_empty() {
				self.debug("No recipient or envelope address.").await?;
				rcpt.insert(self.recipients.get("_")
					.ok_or(anyhow!("Missing default address in recipient table."))?);
			};

			// prepating message header
			let mut reply: Vec<Cow<'_, str>> = vec![];
			if let Some(subject) = mail.subject() {
				reply.push(format!("**Subject:** `{}`", subject).into());
			} else if let Some(thread) = mail.thread_name() {
				reply.push(format!("**Thread:** `{}`", thread).into());
			}
			reply.push(format!("**From:** `{}`", headers.from).into());
			reply.push("".into());
			let header_size = reply.join("\n").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(anyhow!("Failed to extract text from message."))?;
				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(anyhow!("Failed to get text part from message"))?);
				text_num += 1;
			}
			while file_num < attachments {
				files_to_send.push(mail.attachment(file_num)
					.ok_or(anyhow!("Failed to get file part from message"))?);
				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).parse_mode(MarkdownV2)
						} else {
							item
						};
						files.push(InputMedia::Document(item));
					}
					self.sendgroup(chat, files).await?;
				} else {
					self.send(chat, &msg).await?;
				}
			}
		} else {
			bail!("No headers.");
		}
		Ok(())
	}

	/// Send media to specified user
	pub async fn sendgroup<M>(&self, to: &ChatId, media: M) -> Result<Vec<Message>>
	where M: IntoIterator<Item = InputMedia> {
		Ok(self.tg.send_media_group(*to, media).await?)
	}
}

impl mailin_embedded::Handler for TelegramTransport {
	/// Just deny login auth
	fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
		INVALID_CREDENTIALS
	}

	/// Just deny plain auth
	fn auth_plain (&mut self, _authorization_id: &str, _authentication_id: &str, _password: &str) -> Response {
		INVALID_CREDENTIALS
	}

	/// Verify whether address is deliverable
	fn rcpt (&mut self, to: &str) -> Response {
		if self.relay {
			OK
		} else {
			match self.recipients.get(to) {
				Some(_) => OK,
				None => {
					if self.relay {
						OK
					} else {
						NO_MAILBOX
					}
				}
			}
		}
	}

	/// Save headers we need
	fn data_start (&mut self, _domain: &str, from: &str, _is8bit: bool, to: &[String]) -> Response {
		self.headers = Some(SomeHeaders{
			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!("Failed to contact Telegram:\n{:?}", err);
				};
			};
		});
		// clear - just in case
		self.data = vec![];
		self.headers = None;
		result
	}
}

#[async_std::main]
async fn main() -> Result<()> {
	let settings: config::Config = config::Config::builder()
		.set_default("listen_on", "0.0.0.0:1025").unwrap()
		.set_default("hostname", "smtp.2.tg").unwrap()
		.set_default("unknown", "relay").unwrap()
		.add_source(config::File::with_name("smtp2tg.toml"))
		.build()
		.expect("[smtp2tg.toml] there was an error reading config\n\
			\tplease consult \"smtp2tg.toml.example\" for details");



	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(())
















}