Sample code for 30+ languages & platforms
Rust

Mailgun Send Send HTML Email with Attachments and HTML Images

See more Mailgun Examples

Sends an HTML email with images and attachments.

Chilkat Rust Downloads

Rust

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let http = chilkat::Http::new();

http.set_login("api");
http.set_password("sending_api_key");// Replace with your actual sending API key.

let req = chilkat::HttpRequest::new();
req.set_http_verb("POST");
req.set_path("/v3/YOUR_DOMAIN_NAME/messages");
req.set_content_type("multipart/form-data");

// Change YOUR_DOMAIN_NAME to something like "mg.your-domain.com".
req.add_param("from", "Your Name <mailgun@YOUR_DOMAIN_NAME>");
req.add_param("to", "Joe Example <joe@example.com>");
req.add_param("subject", "Hello Joe Example");
req.add_param("html", "<html><body><b>This is the HTML body</b><br><img src=\"cid:cidStarfish.jpg\"></body></html>");

// An a attachd file
let bd = chilkat::BinData::new();
if bd.load_file("qa_data/hamlet.zip").is_err() {
    println!("Failed to load file attachment.");
    return;
}

let _ = req.add_bd_for_upload("attachment", "hamlet.zip", &bd, "application/zip");

// add an image as CID
if bd.load_file("qa_data/jpg/starfish.jpg").is_err() {
    println!("Failed to load HTML image.");
    return;
}

let _ = req.add_bd_for_upload("inline", "cidStarfish.jpg", &bd, "image/jpeg");

let resp = chilkat::HttpResponse::new();
if http.http_s_req("api.mailgun.net", 443, true, &req, &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let sb_response_body = chilkat::StringBuilder::new();
let _ = resp.get_body_sb(&sb_response_body);
let j_resp = chilkat::JsonObject::new();
let _ = j_resp.load_sb(&sb_response_body);
j_resp.set_emit_compact(false);

println!("Response Body:");
println!("{}", j_resp.emit().unwrap_or_default());

let resp_status_code = resp.status_code();
println!("Response Status Code = {}", resp_status_code);
if resp_status_code >= 400 {
    println!("Response Header:");
    println!("{}", resp.header());
    println!("Failed.");
    return;
}

// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)

// {
//   "id": "<20210429234809.1.2D550E1C94D3D98F@sandbox0e542e4c577f4bbb98c8bf6b6bca727b.mailgun.org>",
//   "message": "Queued. Thank you."
// }

// Sample code for parsing the JSON response...
// Use the following online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON

let id = j_resp.string_of("id").unwrap_or_default();
let message = j_resp.string_of("message").unwrap_or_default();