React Native
React Native
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 React Native Downloads
import { Email, MailMan, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
// 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.
const mailman = new MailMan();
// Use your SMTP server hostname. This example uses office365, but it could be any SMTP server..
mailman.smtpHost = 'outlook.office365.com';
mailman.smtpPort = 587;
mailman.startTLS = true;
// Set the SMTP login/password
mailman.smtpUsername = 'OFFICE365-SMTP-LOGIN';
mailman.smtpPassword = 'OFFICE365-SMTP-PASSWORD';
// Create a new email object
const email = new Email();
email.subject = 'HTML Email with embedded CSS';
email.from = 'Chilkat Support <my-office365-user@mydomain.com>';
email.addTo('Chilkat Support', 'support@chilkatsoft.com');
const sbCss = new StringBuilder();
const 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.
const filenameInHtml = 'styles.css';
let contentIdCss: string;
try {
contentIdCss = email.addRelatedString(filenameInHtml, sbCss.getAsString(), 'utf-8');
} catch {
console.log(email.lastErrorText);
return;
}
// The src attribute for the image tag is set to the contentIdCss:
const 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);
const numReplacements = sbHtml.replace('CONTENT_ID_CSS', contentIdCss);
email.setHtmlBody(sbHtml.getAsString());
try {
await mailman.sendEmailAsync(email);
console.log('Mail Sent!');
} catch {
console.log(mailman.lastErrorText);
}
}