Java
Chilkat2 Java
S/MIME Encrypt .eml without Sending
See more Email Object Examples
Demonstrates how to encrypt an email using the recipient's digital certificate. This example just encrypts, and does not send the email.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.MailMan;
import com.chilkatsoft.chilkat2.StringBuilder;
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.
Email email = new Email();
try {
email.loadEml("c:/temp/email/unencrypted.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
email.setPkcs7CryptAlg("aes-gcm");
email.setPkcs7KeyLength(256);
email.setOaepPadding(true);
email.setOaepHash("sha256");
email.setOaepMgfHash("sha256");
Cert cert = new Cert();
try {
cert.loadFromFile("c/temps/cert/recipient.cer");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
email.setSendEncrypted(true);
email.setEncryptCert(cert);
StringBuilder sbSmime = new StringBuilder();
// The mailman object applies the encryption by rendering the email according to the instructions (property settings) provided in the email object.
// No email is sent.
MailMan mailman = new MailMan();
try {
mailman.renderToMimeSb(email, sbSmime);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
sbSmime.writeFile("c:/temp/encryptedEmail.eml", "utf-8", false);
} catch (ChilkatException e) {
System.out.println(mailman.getLastErrorText());
return;
}
System.out.println("Success!");
}
}