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
use http_req::{
request::{Method, Request},
uri::Uri,
};
use lazy_static::lazy_static;
use serde::Serialize;
use urlencoding::encode;
lazy_static! {
static ref SENDGRID_API_PREFIX: String = String::from(
std::option_env!("SENDGRID_API_PREFIX")
.unwrap_or("https://sendgrid-flows-integration.vercel.app/api")
);
}
extern "C" {
fn get_flows_user(p: *mut u8) -> i32;
fn set_error_log(p: *const u8, len: i32);
}
#[derive(Debug, Serialize)]
pub struct Email {
pub to: Vec<String>,
pub subject: String,
pub content: String,
}
pub fn send_email(sender: &str, email: &Email) -> Result<(), String> {
unsafe {
let mut flows_user = Vec::<u8>::with_capacity(100);
let c = get_flows_user(flows_user.as_mut_ptr());
flows_user.set_len(c as usize);
let flows_user = String::from_utf8(flows_user).unwrap();
let mut writer = Vec::new();
let uri = format!(
"{}/{}/send_email?sender={}",
SENDGRID_API_PREFIX.as_str(),
flows_user,
encode(sender),
);
let uri = Uri::try_from(uri.as_str()).unwrap();
let body = serde_json::to_vec(email).unwrap_or_default();
match Request::new(&uri)
.method(Method::POST)
.header("Content-Type", "application/json")
.header("Content-Length", &body.len())
.body(&body)
.send(&mut writer)
{
Ok(res) => {
if !res.status_code().is_success() {
set_error_log(writer.as_ptr(), writer.len() as i32);
return Err(String::from_utf8_lossy(&writer).into_owned());
}
}
Err(e) => {
let e = e.to_string();
set_error_log(e.as_ptr(), e.len() as i32);
return Err(e);
}
}
}
Ok(())
}