Sample code for 30+ languages & platforms
Java

Find Certificate for Email Encryption

Demonstrates finding the recipient's certificate in the Windows certificate store and using it to send encrypted email.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Cert;
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.

        MailMan mailman = new MailMan();

        // Set the SMTP server.
        mailman.setSmtpHost("smtp.example.com");

        // Create a new email object
        Email email = new Email();

        email.setSubject("This email is encrypted");
        email.setBody("This is a digitally encrypted mail");
        email.setFrom("Joe <joe@example.com>");
        // Emails are encrypted using the recipient's certificate.
        String recipientEmailAddr = "jane@example2.com";
        email.addTo("Jane", recipientEmailAddr);

        // Indicate that the email is to be sent encrypted.
        email.setSendEncrypted(true);

        // This example demonstrates finding the email encryption certificate
        // on a Windows system where the certificate is stored in the Windows
        // certificate store.

        Cert cert = new Cert();
        // The recipient's certificate is used to encrypt.
        // (Because the recipient is the only one in possession of the private key to decrypt.)
        try {
            cert.loadByEmailAddress(recipientEmailAddr);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Specify the certificate to be used for encryption.
        email.setEncryptCert(cert);

        try {
            mailman.sendEmail(email);
            System.out.println("Encrypted Mail Sent!");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
        }
    }
}