Java
Chilkat2 Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.MailMan;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
// 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.
MailMan mailman = new MailMan();
// Use your SMTP server hostname. This example uses office365, but it could be any SMTP server..
mailman.setSmtpHost("outlook.office365.com");
mailman.setSmtpPort(587);
mailman.setStartTLS(true);
// Set the SMTP login/password
mailman.setSmtpUsername("OFFICE365-SMTP-LOGIN");
mailman.setSmtpPassword("OFFICE365-SMTP-PASSWORD");
// Create a new email object
Email email = new Email();
email.setSubject("HTML Email with embedded CSS");
email.setFrom("Chilkat Support <my-office365-user@mydomain.com>");
email.addTo("Chilkat Support", "support@chilkatsoft.com");
StringBuilder sbCss = new StringBuilder();
boolean bCrlf = true;
sbCss.appendLine("body {", bCrlf);
sbCss.appendLine(" background-color: powderblue;", bCrlf);
sbCss.appendLine("}", bCrlf);
sbCss.appendLine("h1 {", bCrlf);
sbCss.appendLine(" color: blue;", bCrlf);
sbCss.appendLine("}", bCrlf);
sbCss.appendLine("p {", bCrlf);
sbCss.appendLine(" color: red;", bCrlf);
sbCss.appendLine("}", bCrlf);
// It's possible to add a CSS file directly by calling AddRelatedFile.
// This example will add the CSS from a string.
String filenameInHtml = "styles.css";
String contentIdCss;
try {
contentIdCss = email.addRelatedString(filenameInHtml, sbCss.getAsString(), "utf-8");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// The src attribute for the image tag is set to the contentIdCss:
StringBuilder sbHtml = new StringBuilder();
sbHtml.appendLine("<!DOCTYPE html>", bCrlf);
sbHtml.appendLine("<html>", bCrlf);
sbHtml.appendLine("<head>", bCrlf);
sbHtml.appendLine(" <link rel=\"stylesheet\" href=\"cid:CONTENT_ID_CSS\">", bCrlf);
sbHtml.appendLine("</head>", bCrlf);
sbHtml.appendLine("<body>", bCrlf);
sbHtml.appendLine("", bCrlf);
sbHtml.appendLine("<h1>This is a heading</h1>", bCrlf);
sbHtml.appendLine("<p>This is a paragraph.</p>", bCrlf);
sbHtml.appendLine("", bCrlf);
sbHtml.appendLine("</body>", bCrlf);
sbHtml.appendLine("</html>", bCrlf);
int numReplacements = sbHtml.replace("CONTENT_ID_CSS", contentIdCss);
email.setHtmlBody(sbHtml.getAsString());
try {
mailman.sendEmail(email);
System.out.println("Mail Sent!");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
}
}
}