use lazy_static::lazy_static;
use crate::commons;
use reqwest::header::AUTHORIZATION;
lazy_static! {
static ref MAILGUN_FROM_EMAIL: &'static str = "something@gmail.com";
static ref MAILGUN_BASE_URL: &'static str = "https://api.mailgun.net";
static ref MAILGUN_DOMAIN: &'static str = "mg.snnmo.com";
static ref MAILGUN_API_KEY: &'static str = "056ddf7685c99845daf57a341bb0dcae-1111-2182470a";
}
use crate::services::newsletter_service::SubscriberEmail;
#[derive(Clone)]
pub struct EmailClient {
http_client: reqwest::Client,
sender: &'static str,
}
#[derive(serde::Serialize, Debug)]
struct SendEmailRequest<'a> {
from: &'a str,
to: &'a str,
subject: &'a str,
html: &'a str,
}
impl Default for EmailClient {
fn default() -> Self {
Self {
http_client: reqwest::Client::new(),
sender: &MAILGUN_FROM_EMAIL,
}
}
}
impl EmailClient {
pub fn new() -> Self {
Self::default()
}
pub async fn send_email(
&self,
recipient: &SubscriberEmail,
subject: &str,
email_body: &str,
) -> Result<(), reqwest::Error> {
let url = format!("{}/v3/{}/messages", *MAILGUN_BASE_URL, *MAILGUN_DOMAIN,);
let request_body = SendEmailRequest {
from: self.sender,
to: recipient.as_ref(),
subject,
html: email_body,
};
let user_basic = commons::base64encode(&format!("api:{}", *MAILGUN_API_KEY));
self.http_client
.post(&url)
.header(AUTHORIZATION, format!("Basic {}", user_basic))
.form(&request_body)
.send()
.await?
.error_for_status()?;
Ok(())
}
}