Java Requires Chilkat v11.0.0+
Java
Sign and encrypt an email with S/MIME
See more Email Object Examples
Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
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) {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Email email = new Email();
try {
email.loadEml("with-attachments.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
Cert signer = new Cert();
try {
signer.loadPfxFile("signer.pfx", "SIGNER_PASSWORD");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
Cert recipient = new Cert();
try {
recipient.loadFromFile("recipient.cer");
email.setSigningCert(signer);
email.setEncryptCert(recipient);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
email.setSigningHashAlg("sha256");
email.setPkcs7CryptAlg("aes");
email.setPkcs7KeyLength(256);
email.setOaepPadding(true);
email.setOaepHash("sha256");
email.setOaepMgfHash("sha256");
email.setSendSigned(true);
email.setSendEncrypted(true);
MailMan mail = new MailMan();
BinData rendered = new BinData();
try {
mail.renderToMimeBd(email, rendered);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
rendered.writeFile("signed-encrypted.eml");
} catch (ChilkatException e) {
System.out.println("Failed: rendered.WriteFile.");
return;
}
System.out.println("Saved signed-encrypted.eml.");
}
}