Sample code for 30+ languages & platforms
React Native

Send HTML Email with Embedded Image Loaded from Memory

See more SMTP Examples

Demonstrates how to compose an HTML email with an embedded image where the image data is loaded directly from memory.

Chilkat React Native Downloads

React Native
import { Email, FileAccess, 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.

  // First load image data into memory.
  // This example loads image data from a file.
  // However, your application could get the image data from any other source, such as
  // from a database.
  const fac = new FileAccess();
  const imageBytes = fac.readEntireFile('qa_data/jpg/starfish.jpg');

  // 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 Image Loaded from In-Memory Bytes';
  email.from = 'Chilkat Support <my-office365-user@mydomain.com>';
  email.addTo('Chilkat Support', 'support@chilkatsoft.com');

  let contentIdStarfish: string;
  try {
    contentIdStarfish = email.addRelatedData('starfish.jpg', imageBytes);
  } catch {
    console.log(email.lastErrorText);
    return;
  }

  // The src attribute for the image tag is set to the contentIdStarfish:
  const sbHtml = new StringBuilder();
  sbHtml.append('<html><body><p>This is an HTML email with an embedded image.</p>');
  sbHtml.append('<p><img src="cid:CONTENT_ID_STARFISH" /></p></body></html>');
  const numReplacements = sbHtml.replace('CONTENT_ID_STARFISH', contentIdStarfish);

  email.setHtmlBody(sbHtml.getAsString());

  try {
    await mailman.sendEmailAsync(email);
    console.log('Mail Sent!');
  } catch {
    console.log(mailman.lastErrorText);
  }
}