Dart
Dart
Send HTML Email with Attachments
See more SMTP Examples
Demonstrates how to send an HTML email with file attachments.Chilkat Dart Downloads
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.
final mailman = CkMailMan();
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
final email = CkEmail();
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.
final String contentIdStarfish;
try {
contentIdStarfish = email.addRelatedFile('qa_data/jpg/starfish.jpg');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// The src attribute for the image tag is set to the contentIdStarfish:
final sbHtml = CkStringBuilder();
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>');
final 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');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Add an attachment where the content is contained in a string.
final content = 'This is the content of the 2nd attached file.';
email.addStringAttachment('someText.txt', content);
// Send the HTML email.
try {
mailman.sendEmail(email);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
try {
mailman.closeSmtpConnection();
} on ChilkatException {
print('Connection to SMTP server not closed cleanly.');
}
print('HTML email with attachments sent!');
}