use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::client::Inner;
use crate::error::Result;
use crate::params;
use super::inbound::InboundEmails;
#[derive(Clone, Debug)]
pub struct Emails {
inner: Arc<Inner>,
pub inbound: InboundEmails,
}
impl Emails {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self {
inbound: InboundEmails::new(Arc::clone(&inner)),
inner,
}
}
pub async fn send(&self, email: impl Serialize) -> Result<SentEmail> {
self.send_idempotent(email, None).await
}
pub async fn send_idempotent(
&self,
email: impl Serialize,
idempotency_key: Option<&str>,
) -> Result<SentEmail> {
let headers: Vec<(String, String)> = idempotency_key
.map(|key| vec![("Idempotency-Key".to_string(), key.to_string())])
.unwrap_or_default();
self.inner
.call_with_headers("POST", "/v1/emails", params::to_body(email)?, &headers)
.await
}
pub async fn batch(&self, emails: impl Serialize) -> Result<BatchSent> {
self.inner
.call("POST", "/v1/emails/batch", params::to_body(emails)?)
.await
}
pub async fn get(&self, id: &str) -> Result<Email> {
let mut email: Email = self
.inner
.call("GET", &format!("/v1/emails/{}", params::encode(id)), None)
.await?;
if email.status.is_none() {
email.status = email.last_event.clone();
}
Ok(email)
}
pub async fn list(&self, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!("/v1/emails{}", params::query(params)?),
None,
)
.await
}
pub async fn analytics(&self, params: impl Serialize) -> Result<Value> {
self.inner
.call(
"GET",
&format!("/v1/emails/analytics{}", params::query(params)?),
None,
)
.await
}
pub async fn update(&self, id: &str, params: impl Serialize) -> Result<Email> {
self.inner
.call(
"PATCH",
&format!("/v1/emails/{}", crate::params::encode(id)),
crate::params::to_body(params)?,
)
.await
}
pub async fn reschedule(&self, id: &str, scheduled_at: &str) -> Result<Email> {
self.update(id, serde_json::json!({ "scheduled_at": scheduled_at }))
.await
}
pub async fn cancel(&self, id: &str) -> Result<Email> {
self.inner
.call(
"POST",
&format!("/v1/emails/{}/cancel", params::encode(id)),
None,
)
.await
}
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct SendEmail {
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_id: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub to: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub html: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<TemplateRef>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub cc: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub bcc: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub reply_to: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<Tag>,
#[serde(skip_serializing_if = "Map::is_empty")]
pub headers: Map<String, Value>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<Attachment>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheduled_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tracking_open: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tracking_click: Option<bool>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
impl SendEmail {
pub fn new(
from: impl Into<String>,
to: impl IntoIterator<Item = impl Into<String>>,
subject: impl Into<String>,
) -> Self {
Self {
from: Some(from.into()),
to: to.into_iter().map(Into::into).collect(),
subject: Some(subject.into()),
..Default::default()
}
}
pub fn from_sender(
sender_id: impl Into<String>,
to: impl IntoIterator<Item = impl Into<String>>,
subject: impl Into<String>,
) -> Self {
Self {
sender_id: Some(sender_id.into()),
to: to.into_iter().map(Into::into).collect(),
subject: Some(subject.into()),
..Default::default()
}
}
pub fn html(mut self, html: impl Into<String>) -> Self {
self.html = Some(html.into());
self
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn template(mut self, template: TemplateRef) -> Self {
self.template = Some(template);
self
}
pub fn cc(mut self, cc: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.cc = cc.into_iter().map(Into::into).collect();
self
}
pub fn bcc(mut self, bcc: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.bcc = bcc.into_iter().map(Into::into).collect();
self
}
pub fn reply_to(mut self, reply_to: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.reply_to = reply_to.into_iter().map(Into::into).collect();
self
}
pub fn tag(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.tags.push(Tag::new(name, value));
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers
.insert(name.into(), Value::String(value.into()));
self
}
pub fn attachment(mut self, attachment: Attachment) -> Self {
self.attachments.push(attachment);
self
}
pub fn scheduled_at(mut self, scheduled_at: impl Into<String>) -> Self {
self.scheduled_at = Some(scheduled_at.into());
self
}
pub fn extra(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.extra.insert(key.into(), value.into());
self
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TemplateRef {
pub id: String,
#[serde(skip_serializing_if = "Map::is_empty", default)]
pub variables: Map<String, Value>,
}
impl TemplateRef {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
variables: Map::new(),
}
}
pub fn variable(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.variables.insert(key.into(), value.into());
self
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Tag {
pub name: String,
pub value: String,
}
impl Tag {
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Attachment {
pub filename: String,
pub content: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub content_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub content_id: Option<String>,
}
impl Attachment {
pub fn from_bytes(filename: impl Into<String>, content: impl AsRef<[u8]>) -> Self {
use base64::Engine as _;
Self {
filename: filename.into(),
content: base64::engine::general_purpose::STANDARD.encode(content),
content_type: None,
content_id: None,
}
}
pub fn from_base64(filename: impl Into<String>, content: impl Into<String>) -> Self {
Self {
filename: filename.into(),
content: content.into(),
content_type: None,
content_id: None,
}
}
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn content_id(mut self, content_id: impl Into<String>) -> Self {
self.content_id = Some(content_id.into());
self
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct SentEmail {
pub id: String,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct BatchSent {
pub data: Vec<SentEmail>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Email {
pub id: String,
#[serde(default)]
pub object: Option<String>,
#[serde(default)]
pub from: Option<String>,
#[serde(default)]
pub to: Option<Value>,
#[serde(default)]
pub subject: Option<String>,
#[serde(default)]
pub last_event: Option<String>,
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub mode: Option<String>,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub scheduled_at: Option<String>,
#[serde(default)]
pub error: Option<String>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}