Sample code for 30+ languages & platforms
Dart

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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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.
  final mailman = CkMailMan();

  // 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
  final email = CkEmail();
  email.subject = 'HTML Email with embedded CSS';
  email.from = 'Chilkat Support <my-office365-user@mydomain.com>';
  email.addTo('Chilkat Support', 'support@chilkatsoft.com');

  final sbCss = CkStringBuilder();
  final 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.
  final filenameInHtml = 'styles.css';
  final String contentIdCss;
  try {
    contentIdCss = email.addRelatedString(filenameInHtml, sbCss.getAsString(), 'utf-8');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // The src attribute for the image tag is set to the contentIdCss:
  final sbHtml = CkStringBuilder();
  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);

  final numReplacements = sbHtml.replace('CONTENT_ID_CSS', contentIdCss);

  email.setHtmlBody(sbHtml.getAsString());

  try {
    mailman.sendEmail(email);
    print('Mail Sent!');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
  }
}