Rust
Rust
Send HTML Email with External CSS as Related Item
See more SMTP Examples
Demonstrates how to compose an HTML email with an external CSS file included as a related item and referenced by CID (Content-ID).Chilkat Rust Downloads
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// The mailman object is used for sending and receiving email.
let mailman = chilkat::MailMan::new();
// Use your SMTP server hostname. This example uses office365, but it could be any SMTP server..
mailman.set_smtp_host("outlook.office365.com");
mailman.set_smtp_port(587);
mailman.set_start_tls(true);
// Set the SMTP login/password
mailman.set_smtp_username("OFFICE365-SMTP-LOGIN");
mailman.set_smtp_password("OFFICE365-SMTP-PASSWORD");
// Create a new email object
let email = chilkat::Email::new();
email.set_subject("HTML Email with embedded CSS");
email.set_from("Chilkat Support <my-office365-user@mydomain.com>");
let _ = email.add_to("Chilkat Support", "support@chilkatsoft.com");
let sb_css = chilkat::StringBuilder::new();
let b_crlf = true;
let _ = sb_css.append_line("body {", b_crlf);
let _ = sb_css.append_line(" background-color: powderblue;", b_crlf);
let _ = sb_css.append_line("}", b_crlf);
let _ = sb_css.append_line("h1 {", b_crlf);
let _ = sb_css.append_line(" color: blue;", b_crlf);
let _ = sb_css.append_line("}", b_crlf);
let _ = sb_css.append_line("p {", b_crlf);
let _ = sb_css.append_line(" color: red;", b_crlf);
let _ = sb_css.append_line("}", b_crlf);
// It's possible to add a CSS file directly by calling AddRelatedFile.
// This example will add the CSS from a string.
let filename_in_html = "styles.css".to_string();
let Ok(content_id_css) = email.add_related_string(&filename_in_html, &sb_css.get_as_string().unwrap_or_default(), "utf-8") else {
println!("{}", email.last_error_text());
return;
};
// The src attribute for the image tag is set to the contentIdCss:
let sb_html = chilkat::StringBuilder::new();
let _ = sb_html.append_line("<!DOCTYPE html>", b_crlf);
let _ = sb_html.append_line("<html>", b_crlf);
let _ = sb_html.append_line("<head>", b_crlf);
let _ = sb_html.append_line(" <link rel=\"stylesheet\" href=\"cid:CONTENT_ID_CSS\">", b_crlf);
let _ = sb_html.append_line("</head>", b_crlf);
let _ = sb_html.append_line("<body>", b_crlf);
let _ = sb_html.append_line("", b_crlf);
let _ = sb_html.append_line("<h1>This is a heading</h1>", b_crlf);
let _ = sb_html.append_line("<p>This is a paragraph.</p>", b_crlf);
let _ = sb_html.append_line("", b_crlf);
let _ = sb_html.append_line("</body>", b_crlf);
let _ = sb_html.append_line("</html>", b_crlf);
let num_replacements = sb_html.replace("CONTENT_ID_CSS", &content_id_css);
email.set_html_body(&sb_html.get_as_string().unwrap_or_default());
if mailman.send_email(&email).is_err() {
println!("{}", mailman.last_error_text());
} else {
println!("Mail Sent!");
}