Java
Chilkat2 Java
Send Email With Attachments
See more SMTP Examples
Demonstrates how to send an email with attachments.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.MailMan;
public class ChilkatExample {
public static void main(String[] args) {
// 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 (SMTP) and receiving (POP3) email.
MailMan mailman = new MailMan();
// Set the SMTP server.
mailman.setSmtpHost("smtp.my-tls-mail-server.com");
// Set the SMTP login/password (if required)
mailman.setSmtpUsername("MY_SMTP_USERNAME");
mailman.setSmtpPassword("MY_SMTP_PASSWORD");
// Connect to SMTP port 465 using TLS.
mailman.setSmtpSsl(true);
mailman.setSmtpPort(465);
// Create a new email object
Email email = new Email();
email.setSubject("This is a test");
email.setBody("This is a test");
email.setFrom("Chilkat Support <support@chilkatsoft.com>");
email.addTo("Chilkat Admin", "admin@chilkatsoft.com");
// To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.
// Add some attachments.
// The AddFileAttachment method returns the value of the content-type it chose for the attachment.
String contentType;
try {
contentType = email.addFileAttachment("qa_data/jpg/starfish.jpg");
contentType = email.addFileAttachment("qa_data/pdf/fishing.pdf");
// Call SendEmail to connect to the SMTP server and send.
// The connection (i.e. session) to the SMTP server remains
// open so that subsequent SendEmail calls may use the
// same connection.
mailman.sendEmail(email);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
mailman.closeSmtpConnection();
} catch (ChilkatException e) {
System.out.println("Connection to SMTP server not closed cleanly.");
}
System.out.println("Mail with attachments sent!");
}
}