Echo Writes Code

forms.rs

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
use crate::errors::{ Error, Result };
use crate::state::{ ApplicationState };

use serde::{ Deserialize };

#[derive(Deserialize)]
pub(crate) struct Contact {
	pub(crate) email: String,
	pub(crate) name: String,
	pub(crate) pronouns: String,
	pub(crate) organization: String,
	pub(crate) subject: String,
	pub(crate) message: String,
}

impl Contact {
	pub(crate) async fn send_email(&self, state: &ApplicationState) -> Result<()> {
		let Some(contact_email) = state.content.contact_email() else {
			return Err(Error::MissingContactEmail);
		};

		if self.email.is_empty() {
			return Err(Error::MissingFormField("email".to_string()));
		}

		if self.name.is_empty() {
			return Err(Error::MissingFormField("name".to_string()));
		}

		if self.subject.is_empty() {
			return Err(Error::MissingFormField("subject".to_string()));
		}

		if self.message.is_empty() {
			return Err(Error::MissingFormField("message".to_string()));
		}

		let pronouns_text =
			if self.pronouns.is_empty() {
				"".to_string()
			} else {
				format!(" ({})", self.pronouns)
			};

		let organization_text =
			if self.organization.is_empty() {
				"".to_string()
			} else {
				format!(" on behalf of {}", self.organization)
			};

		let subject = format!("[Via contact form] {}", self.subject);
		let body = format!("{}\n\n{}{}{}\n{}", self.message, self.name, pronouns_text, organization_text, self.email);

		state.email_client.send(&contact_email, &subject, &body)
			.await?;

		Ok(())
	}
}