React Native
React Native
Send HTML Email with Attachments
See more SMTP Examples
Demonstrates how to send an HTML email with file attachments.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.
const mailman = new MailMan();
mailman.smtpHost = 'smtp.my-starttls-mail-server.com';
mailman.smtpUsername = 'MY-SMTP-USERNAME';
mailman.smtpPassword = 'MY-SMTP-PASSWORD';
mailman.startTLS = true;
mailman.smtpPort = 587;
// Create a new email object
const email = new Email();
email.subject = 'Test SMTP API to Send HTML Email with Attachments';
email.from = 'Joe Programmer <joe@my-starttls-mail-server.com>';
email.addTo('Chilkat Support', 'support@chilkatsoft.com');
// Add a plain-text alternative body, which will likely never be seen.
// (It is shown if the receiving email client is incapable of displaying HTML email.)
email.addPlainTextAlternativeBody('This is a plain-text alternative body...');
// Our HTML will include an image, so add the related image here.
let contentIdStarfish: string;
try {
contentIdStarfish = email.addRelatedFile('qa_data/jpg/starfish.jpg');
} 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.addHtmlAlternativeBody(sbHtml.getAsString());
// Finally, add some attachments to the email.
// Add a file attachment.
try {
email.addFileAttachment2('qa_data/pdf/fishing.pdf', 'application/pdf');
} catch {
console.log(email.lastErrorText);
return;
}
// Add an attachment where the content is contained in a string.
const content = 'This is the content of the 2nd attached file.';
email.addStringAttachment('someText.txt', content);
// Send the HTML email.
try {
await mailman.sendEmailAsync(email);
} catch {
console.log(mailman.lastErrorText);
return;
}
try {
await mailman.closeSmtpConnectionAsync();
} catch {
console.log('Connection to SMTP server not closed cleanly.');
}
console.log('HTML email with attachments sent!');
}