Message

Struct Message 

Source
pub struct Message {
Show 17 fields pub to: Option<Recipients>, pub cc: Option<Recipients>, pub bcc: Option<Recipients>, pub from_email: String, pub from_name: String, pub subject: Option<String>, pub text_part: Option<String>, pub html_part: Option<String>, pub recipients: Option<Recipients>, pub attachments: Option<Vec<Attachment>>, pub inline_attachments: Option<Vec<Attachment>>, pub vars: Option<Map<String, Value>>, pub mj_template_id: Option<usize>, pub use_mj_template_language: Option<bool>, pub mj_custom_id: Option<String>, pub mj_event_payload: Option<String>, pub headers: Option<HashMap<String, String>>,
}
Expand description

§Mailjet Send API v3 Message

§Basic Message

A Message is created and sent to the Recipient defined. This message neither contains HTML or is consuming a template, instead this Message contains raw text.

use mailjet_rs::common::Recipient;
use mailjet_rs::v3::Message;
use mailjet_rs::{Client, SendAPIVersion};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Create an instance of the Mailjet API client
    // used to send the `Message` and also define your API
    // credentials
    let client = Client::new(
        SendAPIVersion::V3,
        "public_key",
        "private_key",
    );

    // Create your a `Message` instance with the minimum required values
    let mut message = Message::new(
        "mailjet_sender@company.com",
        "Mailjet Rust",
        Some("Your email flight plan!".to_string()),
        Some("Dear passenger, welcome to Mailjet! May the delivery force be with you!".to_string())
    );

    message.push_recipient(Recipient::new("receiver@company.com"));

    // Finally send the message using the `Client`
    let response = client.send(message).await;

    // Do something with the response from Mailjet
    // Ok(Response { sent: [Sent { email: "your_receiver@company.com", message_id: 000, message_uuid: "message-uuid" }] })
    println!("{:?}", response);

    Ok(())
}

§Send to multiple recipients

use mailjet_rs::common::Recipient;
use mailjet_rs::v3::Message;
use mailjet_rs::{Client, SendAPIVersion};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let client = Client::new(
        SendAPIVersion::V3,
        "public_key",
        "private_key",
    );

    let mut message = Message::new(
        "mailjet_sender@company.com",
        "Mailjet Rust",
        Some("Your email flight plan!".to_string()),
        Some("Dear passenger, welcome to Mailjet! May the delivery force be with you!".to_string())
    );

    let recipients = vec![
        Recipient::new("receiver1@company.com"),
        Recipient::new("receiver2@company.com"),
        Recipient::new("receiver3@company.com"),
    ];

    message.push_many_recipients(recipients);

    let response = client.send(message).await;

    println!("{:?}", response);

    Ok(())
}

§Using To, Cc and Bcc instead of Recipients

Note: If a recipient does not exist in any of your contact list it will be created from scratch, keep that in mind if you are planning on sending a welcome email and then you’re trying to add the email to a list as the contact effectively exists already. Mailjet’s API Documentation

use mailjet_rs::common::Recipient;
use mailjet_rs::v3::Message;
use mailjet_rs::{Client, SendAPIVersion};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let client = Client::new(
        SendAPIVersion::V3,
        "public_key",
        "private_key",
    );

    let mut message = Message::new(
        "mailjet_sender@company.com",
        "Mailjet Rust",
        Some("Your email flight plan!".to_string()),
        Some("Dear passenger, welcome to Mailjet! May the delivery force be with you!".to_string())
    );

    message.set_receivers(
        vec![
            Recipient::new("bar@foo.com"),
        ],
        Some(vec![
            Recipient::new("bee@foo.com"),
        ]),
        None
    );

    let response = client.send(message).await;

    println!("{:?}", response);

    Ok(())
}

§Send Inline Attachments

use mailjet_rs::common::Recipient;
use mailjet_rs::v3::{Message, Attachment};
use mailjet_rs::{Client, SendAPIVersion};

/// Base64 representation of the Mailjet logo found in the Mailjet SendAPI V3 docs
const MAILJET_LOGO_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4wIIChcxurq5eQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABV0lEQVQokaXSPWtTYRTA8d9N7k1zm6a+RG2x+FItgpu66uDQxbFurrr5OQQHR9FZnARB3PwSFqooddAStCBoqmLtS9omx+ESUXuDon94tnP+5+1JYm057GyQjZFP+l+S6G2FzlNe3WHtHc2TNI8zOlUUGLxsD1kDyR+EEQE2P/L8Jm/uk6RUc6oZaYM0JxtnpEX9AGPTtM6w7yzVEb61EaSNn4QD3j5m4QabH6hkVFLSUeqHyCeot0ib6BdNVGscPM/hWWr7S4Tw9TUvbpFUitHTnF6XrS+sL7O6VBSausT0FZonSkb+nZUFFm+z8Z5up5Btr1Lby7E5Zq4yPrMrLR263ZV52g+LvfW3iy6PXubUNVrnhqYNF3bmiZ1i1MmLnL7OxIWh4T+IMpYeRNyrRzyZjWg/ioh+aVgZu4WfXxaixbsRve5fiwb8epTo8+kZjSPFf/sHvgNC0/mbjJbxPAAAAABJRU5ErkJggg==";


#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let client = Client::new(
        SendAPIVersion::V3,
        "public_key",
        "private_key",
    );

    let mut message = Message::new(
        "mailjet_sender@company.com",
        "Mailjet Rust",
        Some("Your email flight plan!".to_string()),
        Some("Dear passenger, welcome to Mailjet! May the delivery force be with you!".to_string())
    );

    message.set_receivers(
        vec![
            Recipient::new("bar@foo.com"),
        ],
        Some(vec![
            Recipient::new("bee@foo.com"),
        ]),
        None
    );

    let mailjet_logo = Attachment::new(
        "image/png",
        "logo.png",
        MAILJET_LOGO_BASE64);

    message.attach_inline(mailjet_logo);

    message.html_part = Some("<h3>Dear [[var:name]] [[var:last]], welcome to <img src=\"cid:logo.png\"> <a href=\"https://www.mailjet.com/\">Mailjet</a>!<br />May the delivery force be with you!".to_string());


    let response = client.send(message).await;

    println!("{:?}", response);

    Ok(())
}

The following is an example using the Mailjet’s Send API v3 where the following features are covered:

  • Attach inline images
  • Attach files
  • Use template variables
use mailjet_rs::common::Recipient;
use mailjet_rs::v3::{Message, Attachment};
use mailjet_rs::{Client, SendAPIVersion};
use mailjet_rs::{Map, Value};

/// Base64 representation of the Mailjet logo found in the Mailjet SendAPI V3 docs
const MAILJET_LOGO_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4wIIChcxurq5eQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABV0lEQVQokaXSPWtTYRTA8d9N7k1zm6a+RG2x+FItgpu66uDQxbFurrr5OQQHR9FZnARB3PwSFqooddAStCBoqmLtS9omx+ESUXuDon94tnP+5+1JYm057GyQjZFP+l+S6G2FzlNe3WHtHc2TNI8zOlUUGLxsD1kDyR+EEQE2P/L8Jm/uk6RUc6oZaYM0JxtnpEX9AGPTtM6w7yzVEb61EaSNn4QD3j5m4QabH6hkVFLSUeqHyCeot0ib6BdNVGscPM/hWWr7S4Tw9TUvbpFUitHTnF6XrS+sL7O6VBSausT0FZonSkb+nZUFFm+z8Z5up5Btr1Lby7E5Zq4yPrMrLR263ZV52g+LvfW3iy6PXubUNVrnhqYNF3bmiZ1i1MmLnL7OxIWh4T+IMpYeRNyrRzyZjWg/ioh+aVgZu4WfXxaixbsRve5fiwb8epTo8+kZjSPFf/sHvgNC0/mbjJbxPAAAAABJRU5ErkJggg==";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

    // Create an instance of the Mailjet API client
    // used to send the `Message` and also define your API
    // credentials
    let client = Client::new(
        SendAPIVersion::V3,
        "public_key",
        "private_key",
    );

    // Create your a `Message` instance with the minimum required values
    let mut message = Message::new(
        "mailjet_sender@company.com",
        "Mailjet Rust",
        Some("Your email flight plan!".to_string()),
        Some("Dear passenger, welcome to Mailjet! May the delivery force be with you!".to_string())
    );

    message.push_recipient(Recipient::new("receiver@company.com"));

    // Set some HTML for your email
    //
    // Note that here we are using `cid:logo.png` as the src value for our image
    // this is using the `inline_attachment` with `filename` "logo.png" as the
    // image source
    message.html_part = Some("<h3>Dear [[var:name]] [[var:last]], welcome to <img src=\"cid:logo.png\"> <a href=\"https://www.mailjet.com/\">Mailjet</a>!<br />May the delivery force be with you!".to_string());

    // Attach inline files providing its base64 representation
    // content-type and a name.
    // The name of the file can be used to reference this file in your HTML content
    let mailjet_logo_inline = Attachment::new(
      "image/png",
      "logo.png",
      MAILJET_LOGO_BASE64);

    // Attach the `Attachment` as an Inline Attachment
    // this function can also be used to attach common Attachments
    message.attach_inline(mailjet_logo_inline);

    // Creates a txt file Attachment
    let txt_file_attachment = Attachment::new(
      "text/plain",
      "test.txt",
      "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK");

    // Attaches the TXT file as an email Attachment
    message.attach(txt_file_attachment);

    // Provide variables for your template
    // `Map` and `Value` are reexported from
    // `serde_json`
    let mut vars = Map::new();

    vars.insert(String::from("name"), Value::from("Foo"));
    vars.insert(String::from("last"), Value::from("Bar"));

    message.vars = Some(vars);

    // Finally send the message using the `Client`
    let response = client.send(message).await;

    // Do something with the response from Mailjet
    // Ok(Response { sent: [Sent { email: "your_receiver@company.com", message_id: 000, message_uuid: "message-uuid" }] })
    println!("{:?}", response);

    Ok(())
}

§Reference

Send API V3

Fields§

§to: Option<Recipients>

The recipients to send the Message

§cc: Option<Recipients>

The carbon copy recipients

§bcc: Option<Recipients>

The blind carbon copy recipients

§from_email: String

The verified sender email address

§from_name: String

The name of the sender

§subject: Option<String>

The subject of the email

§text_part: Option<String>

The raw text content of the email

§html_part: Option<String>

The HTML content of the email

§recipients: Option<Recipients>§attachments: Option<Vec<Attachment>>§inline_attachments: Option<Vec<Attachment>>§vars: Option<Map<String, Value>>

Variables for email templating

§mj_template_id: Option<usize>

ID provided by Passport at the end of your designing process or the ID returned by the /template resource.

§use_mj_template_language: Option<bool>

Flag for Mailjet’s Message to interpret the template language

§mj_custom_id: Option<String>

Custom ID for the email

§mj_event_payload: Option<String>§headers: Option<HashMap<String, String>>

Implementations§

Source§

impl Message

Source

pub fn new( from_email: &str, from_name: &str, subject: Option<String>, text_part: Option<String>, ) -> Self

Creates a new Message Send API v3 instance with the minimum requirements for a Message and remaining fields set as None.

Note that recipients must be defined later, either by using push_recipient, push_many_recipients or set_receivers.

Source

pub fn push_recipient(&mut self, recipient: Recipient)

Pushes a Recipient to the Recipients field of the Message

Source

pub fn push_many_recipients(&mut self, recipients: Recipients)

Pushes every Recipient object into the Recipients field of the Message

Source

pub fn set_receivers( &mut self, to: Recipients, cc: Option<Recipients>, bcc: Option<Recipients>, )

Set the To, Cc and Bcc fields for the Message.

When calling this method any of the fields will be replaced with the values provided on the call.

§Panic

When calling this method with Recipients defined (with a value different to None) this method will panic.

This is because Mailjet’s Send API v3 documentation expects one of two ways to define recipients but never both:

Optionally, in place of Recipients, you can use To, Cc and Bcc properties. To, Cc and Bcc can’t be used in conjunction with Recipients

Mailjet SendAPI V3 Documentation

Source

pub fn attach(&mut self, attachment: Attachment)

Attach an Attachment to the Message The recipient of a email with attachment will have to click to see it. The inline attachment can be visible directly in the body of the message depending of the email client support.

The content will need to be Base64 encoded. You will need to specify the MIME type and a file name.

Remember to keep the size of your attachements low and not to exceed 15 MB.

Source

pub fn attach_inline(&mut self, attachment: Attachment)

Attach an Attachment to the Message When using an inline Attachment, it’s possible to insert the file inside the HTML code of the email by using cid:FILENAME.EXT where FILENAME.EXT is the Filename specified in the declaration of the Attachment.

The content will need to be Base64 encoded. You will need to specify the MIME type and a file name.

Remember to keep the size of your attachements low and not to exceed 15 MB.

Source

pub fn set_template_id(&mut self, id: usize)

Sets the Mj-TemplateID property for the Message and also turns true the Mj-TemplateLanguage.

This method is used when using a template language for your Message

Source

pub fn set_custom_id(&mut self, id: String)

Tag Email Messages

Sets the Mj-CustomID property for the Message.

§Mailjet SendAPI V3

Sometimes you need to use your own ID in addition to ours to be able to trace back the message in our system easily. For this purpose we let you insert your own ID in the message. To achieve this, just pass the ID you want to use in the Mj-CustomID property.

From then, your CustomID is linked to our own Message ID. You can also retrieve the message later by providing it to the /message resource CustomID filter.

curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/message?CustomID=<Your Custom ID>
Source

pub fn set_event_payload(&mut self, payload: String)

Sets the Mj-EventPayload property for the Message.

§Mailjet SendAPI V3

Sometimes, you need more than just an ID to represent the context to what a specific message is attached to. For this purpose, we let you insert a payload in the message which can be of any format (XML, JSON, CSV, etc). To take advantage of this, just pass the payload you want in the Mj-EventPayLoad property.

Source

pub fn set_headers(&mut self, headers: HashMap<String, String>)

Sets the Headers property for the Message.

§Mailjet SendAPI V3

In every message, you can specify your own Email headers using the Headers property. For example, it is possible to specify a Reply-To email address.

Trait Implementations§

Source§

impl Debug for Message

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Message

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Payload for Message

Source§

fn to_json(&self) -> String

Creates the JSON representation of self consumed by Mailjet’s API
Source§

impl Serialize for Message

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,