Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert two commits #71

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,6 @@ services:
networks: [default]
```

## Sample messages

The `sample` directory contains a couple of test messages. These can be sent using by running:

```sh
cd backend/
cargo test send_sample_messages -- --ignored
```

## Development

Install [Rust](https://www.rust-lang.org/learn/get-started) and [Trunk](https://trunkrs.dev/)
Expand Down
22 changes: 9 additions & 13 deletions backend/src/mail_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl MailHandler {
}

impl MailHandler {
fn parse_mail(&mut self) -> Result<MailMessage, &'static str> {
fn parse_mail(&mut self) -> Result<(), &'static str> {
// parse the email and convert it to a internal data structure
let parsed = mail_parser::Message::parse(&self.buffer)
.ok_or("Could not parse email using mail_parser")?;
Expand All @@ -48,10 +48,10 @@ impl MailHandler {

// send the message to a internal queue
self.tx
.send(message.clone())
.send(message)
.map_err(|_| "Could not send email to own broadcast channel")?;

Ok(message)
Ok(())
}
}

Expand Down Expand Up @@ -80,7 +80,7 @@ impl mailin::Handler for MailHandler {
) -> mailin::Response {
event!(
Level::INFO,
"Incoming message on {} from {} to {:?}",
"New email on {} from {} to {:?}",
domain,
from,
to
Expand All @@ -94,16 +94,12 @@ impl mailin::Handler for MailHandler {
}

fn data_end(&mut self) -> mailin::Response {
match self.parse_mail() {
Err(e) => {
event!(Level::WARN, "Error parsing email: {}", e);
if let Err(e) = self.parse_mail() {
event!(Level::WARN, "Error parsing email: {}", e);

mailin::response::Response::custom(500, "Error parsing message".to_string())
}
Ok(message) => mailin::response::Response::custom(
250,
format!("2.0.0 Ok: queued as {}", message.id),
),
mailin::response::Response::custom(500, "Error parsing message".to_string())
} else {
mailin::response::OK
}
}

Expand Down
37 changes: 1 addition & 36 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,9 @@ mod test {
use fake::faker::lorem::en::Paragraph;
use fake::faker::name::en::Name;
use fake::Fake;
use lettre::address::Envelope;
use lettre::message::header::ContentType;
use lettre::message::{Attachment, MultiPart, SinglePart};
use lettre::{Address, Message, SmtpTransport, Transport};
use lettre::{Message, SmtpTransport, Transport};
use std::process::{Command, Stdio};
use tokio::time::{sleep, Duration};

Expand Down Expand Up @@ -297,38 +296,4 @@ mod test {
assert!(messages[2].has_plain);
assert_eq!(messages[2].attachments.len(), 1);
}

#[tokio::test]
#[ignore]
async fn send_sample_messages() {
let smtp_port: u16 = parse_env_var("SMTP_PORT", 1025);
let mut paths = std::fs::read_dir("../samples").unwrap();
let mailer = SmtpTransport::builder_dangerous("127.0.0.1".to_string())
.port(smtp_port)
.build();

while let Some(Ok(entry)) = paths.next() {
let message = std::fs::read_to_string(entry.path()).unwrap();
let mut lines = message.lines();

let sender = lines
.next()
.unwrap()
.trim_start_matches("Sender: ")
.parse::<Address>()
.unwrap();
let recipients = lines
.next()
.unwrap()
.trim_start_matches("Recipients: ")
.split(',')
.map(|r| r.trim().parse::<Address>().unwrap())
.collect::<Vec<Address>>();
let envelope = Envelope::new(Some(sender), recipients).unwrap();

let email = lines.collect::<Vec<&str>>().join("\n");

mailer.send_raw(&envelope, email.as_bytes()).unwrap();
}
}
}
22 changes: 4 additions & 18 deletions backend/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ impl From<MailMessage> for MailMessageMetadata {
#[derive(Clone, Debug, Serialize)]
pub struct Attachment {
filename: String,
content_id: Option<String>,
mime: String,
size: String,
content: String,
Expand All @@ -104,7 +103,6 @@ impl From<&mail_parser::MessagePart<'_>> for Attachment {
Attachment {
filename,
mime,
content_id: part.content_id().map(|s| s.to_owned()),
size: humansize::format_size(part.contents().len(), humansize::DECIMAL),
content: base64::encode(part.contents()),
}
Expand Down Expand Up @@ -150,23 +148,11 @@ impl MailMessage {
self.opened = true;
}

pub fn render(&self) -> String {
pub fn body(&self) -> String {
if self.html.is_empty() {
self.text.clone()
} else {
let mut html = self.html.clone();

for attachement in &self.attachments {
if let Some(content_id) = &attachement.content_id {
let from = format!("cid:{content_id}");
let to = format!("data:{};base64,{}", attachement.mime, attachement.content);

dbg!(&from, &to);
html = html.replace(&from, &to);
}
}

html
self.html.clone()
}
}
}
Expand All @@ -180,7 +166,7 @@ impl TryFrom<mail_parser::Message<'_>> for MailMessage {
_ => {
event!(
Level::WARN,
"Could not parse 'From' address header, setting placeholder address."
"Could not parse 'From' address header, setting placeholder 'from' address."
);

Address {
Expand All @@ -199,7 +185,7 @@ impl TryFrom<mail_parser::Message<'_>> for MailMessage {
_ => {
event!(
Level::WARN,
"Could not parse 'To' address header, setting placeholder address."
"Could not parse 'To' address header, setting placeholder 'to' address."
);

vec![Address {
Expand Down
2 changes: 1 addition & 1 deletion backend/src/web_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ async fn message_body_handler(
) -> Result<Html<String>, StatusCode> {
if let Ok(storage) = state.storage.read() {
match storage.get(&id) {
Some(message) => Ok(Html(message.render())),
Some(message) => Ok(Html(message.body())),
_ => Err(StatusCode::NOT_FOUND),
}
} else {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ pub struct MailMessageMetadata {
#[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct Attachment {
pub filename: String,
pub content_id: Option<String>,
pub mime: String,
pub size: String,
pub content: String,
Expand Down
12 changes: 12 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

# samples

Directory with sample emails.


If you have `swaks` installed, you can do
```sh
samples/swaks_injects samples/*.eml
```
to get those emails into `mailcrab`. If desired,
set and export the environment variables `SMTP_SERVER` and `SMTP_PORT`.
55 changes: 0 additions & 55 deletions samples/cid.email

This file was deleted.

32 changes: 32 additions & 0 deletions samples/multiple_RCPT_TO
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/bin/sh

SVR="${SMTP_SERVER:-127.0.0.1}"
PRT="${SMTP_PORT:-1025}"

swaks \
--helo sample.direct.ry \
--from multi_rcpt_to@script \
--to many@mailcrab,foo@bar,foo@baz,[email protected],[email protected] \
--server ${SVR}:${PRT} \
--data - << HERE
From: Many RCPT TO<recipient@metadata>
To: See Envelope <[email protected]>
Subject: Multiple RCPT TO in one SMTP session
Date: %DATE%

Hi,

This message is for checking
how mailcrab handles multiple RCPT TO in one SMTP session.

Inspirated by
git log --patch 0699315cb2509^1..0699315cb2509

Bye

P.S.
This message proofs
that mailcrab can handle multiple RCPT TO in one SMTP session. :-)
HERE

# l l
22 changes: 0 additions & 22 deletions samples/multiple_recipients.email

This file was deleted.

36 changes: 0 additions & 36 deletions samples/no_from.email

This file was deleted.

8 changes: 8 additions & 0 deletions samples/no_from.eml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
To: Re Viewer <[email protected]>
Subject: No from

Hi,

This test email has no From: in DATA

Bye.
Loading