sendgrid_async/sendgrid/
client.rs

1use http_types::{Body, Error, Request, Result, StatusCode, Url};
2use std::env;
3
4use super::*;
5
6/// Base url for the Sendgrid API.
7const DEFAULT_BASE_URL: &str = "https://api.sendgrid.com/v3/";
8
9/// Entrypoint for interacting with the SendGrid API.
10pub struct Client {
11    base_url: Url,
12    key: String,
13}
14
15impl Client {
16    /// Create a new SendGrid client struct..
17    pub fn new<K>(key: K) -> Self
18    where
19        K: Into<String>,
20    {
21        Self {
22            base_url: Url::parse(DEFAULT_BASE_URL).expect("error parsing DEFAULT_BASE_URL"),
23            key: key.into(),
24        }
25    }
26
27    /// Create a new SendGrid client struct from environment variables.
28    pub fn new_from_env() -> Self {
29        let key = env::var("SENDGRID_API_KEY").expect("SENDGRID_API_KEY env variable not set");
30        Client::new(key)
31    }
32
33    /// Get the currently set API key.
34    pub fn key(&self) -> &str {
35        &self.key
36    }
37
38    pub fn url(&self, path: &str) -> Result<Url> {
39        Ok(self.base_url.join(path)?)
40    }
41
42    /// Send a sendgrid message.
43    pub async fn send_message(&self, message: &Message) -> Result<()> {
44        let url = self.url("mail/send")?;
45        let mut request = Request::post(url);
46        self.set_authorization_header(&mut request)?;
47        request.set_body(Body::from_json(message)?);
48
49        let mut resp = crate::http_client::execute(request).await?;
50        match resp.status() {
51            StatusCode::Accepted => Ok(()),
52            s => {
53                let body = resp.body_string().await?;
54                let error = anyhow::Error::msg(body);
55                Err(Error::new(s, error))
56            }
57        }
58    }
59
60    pub fn set_authorization_header(&self, req: &mut Request) -> Result<()> {
61        use http_types::headers::*;
62        let bt = format!("Bearer {}", self.key);
63        let bearer = HeaderValue::from_bytes(bt.into_bytes())?;
64        req.append_header(AUTHORIZATION, bearer);
65        Ok(())
66    }
67}