The below mentioned is a working sample use it.
import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertStore;
import java.security.cert.CollectionCertStoreParameters;
import java.security.Security;
import java.security.MessageDigest;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.MessagingException;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Authenticator;
import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.smtp.SMTPTransport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.*;
import javax.mail.*;
import javax.activation.*;//for DataSource
//*********************
import com.sun.crypto.provider.JceKeyStore;
//**********************
import java.security.cert.X509Certificate;
import com.sun.net.ssl.internal.ssl.Provider;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute;
import org.bouncycastle.asn1.smime.SMIMECapability;
import org.bouncycastle.asn1.smime.SMIMECapabilityVector;
import org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.X509V3CertificateGenerator;
import org.bouncycastle.mail.smime.SMIMESignedGenerator;
import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator;
import org.bouncycastle.jce.provider.*;
//*********************
/**
* <TITLE> Send</TITLE>
* This class handles the creation of email, signing, encryption and dispatching the email to the client.
*
*@author Basit Hussain
*@fileSend.java
*@version 1.0
*@date30/08/2004
*/
public class Send{
private PrivateKey senderKey = null;
private X509Certificate caCert = null;
private X509Certificate senderCert = null;
private X509Certificate rcptCert = null;
static ReadConfig prop;
private Session session = null;
private boolean octContent = false;
private boolean sent = false;
private ArrayList pdfFiles;
private String xmlFile;
private String html1 = "";
private String html2 = "";
private String html3 = "";
private String html4 = "";
private String html5 = "";
private String html6 = "";
private String fileNames[] = new String[1];
private String email="";
//following flag is used as only a patch that if there is no certificate
//for an email..it will become true and throw the control back to the
//PDFGenerator class with the notification that the email was sent.
public boolean noCert=false;
//public POSEstmtLog log;
Transport transport;
DataOutputStream dos;
public Send(String configFile,int merchantNo,String[] fileNames,String merchantemail)
{
this.fileNames = fileNames;
prop = new ReadConfig(configFile);
email = merchantemail;
}
/**
*This method is the caller to send the complete email to the specified client.
*It handles the complete flow.
*@returnint -Status code to confirm the status of the email.
*/
public int SendMail() {
try {
Security.addProvider(new BouncyCastleProvider());
try
{
sent=false;
noCert = false;
boolean isSigning = true;
boolean isEncrypting = true;
String host = prop.getProperty("SMTP_SERVER");
System.setProperty("mail.smtp.host",host);
System.setProperty("mail.smtp.auth","true");
String sender = prop.getProperty("SENDER");
String rcpt= email; //recipient email address
String replyto = prop.getProperty("REPLY_TO");
session = Session.getDefaultInstance(System.getProperties(), null);
//FIXED BUG 2: The matching of email to certificate shuould not be case sensitive
String tempMail = email.toLowerCase();
if(noCert)
{
return 2;
}
senderCert = getCert(prop.getProperty("CERT"),email);
senderKey = getKey(prop.getProperty("P12"), prop.getProperty("ALIAS"));
//*****************
// plain message
System.out.println("After creating message");
//new
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender,"QNB"));
InternetAddress[] to2 = { new InternetAddress(rcpt)};
InternetAddress[] replyto2 = { new InternetAddress(replyto)};
msg.setRecipients(Message.RecipientType.TO, rcpt);
msg.setReplyTo(replyto2);
msg.setSubject("Your Merchant e-Statement");
msg.setSentDate(new Date());
//msg.setContent(mb.getContent(),mb.getContentType());
msg.saveChanges();
MimeBodyPart plainMsg = createMessage(sender, rcpt, replyto);//files attached
////////--
//***** --SIGNING
MimeMultipart mmp = sign(plainMsg);
System.out.println("After Signing");
msg.setContent(mmp);
msg.saveChanges();
System.out.println("set MEssage");
String sss[]= {"Content-Type:","To:"};
Enumeration e = msg.getAllHeaderLines();
msg.saveChanges();
System.out.println("after save changes");
transport=null;////trial
transport = session.getTransport("smtp");
System.out.println("after getting transport");
transport.connect(host,prop.getProperty("SMTP_USERNAME"),prop.getProperty("SMTP_PASSWORD"));
System.out.println("b4 sending");
transport.sendMessage(msg,msg.getAllRecipients());
sent = true;
transport.close();
}///end of inner try
catch(Exception mex)
{
sent = false;
try
{
transport.close();
}
catch(Exception ex)
{
Thread.sleep(5000);
}
if(mex instanceof java.net.SocketException)
{
System.out.println("SOCKET EXCEPTION");
Thread.sleep(5000);
}
}
}
catch (Exception e) {
e.printStackTrace();
System.exit(0); //////TESTING WHICH CASE IT FAILS.
}
if(sent)
{
return 1;
}
else
{
return 0;
}
}
/**
*This method creates the complete email package with the attachments.
*@param from - Email Sender
*@paramto- Email Receiver
*@returnMimeBodyPart Required in the SendMail() method.
*/
private MimeBodyPart createMessage(String from, String to, String replyto)
{
try {
MimeBodyPart m = null;
{
BodyPart mbp_text = new MimeBodyPart();
//*****addition on 20/01/2004
mbp_text.setContent(html1+html2+html3+html4+html5,"text/html");
//****
//***Adding the Attachment
//attaching the PDF************
System.out.println("FILE ATTACHING");
MimeMultipart mp = new MimeMultipart();
//adding text part
mp.addBodyPart(mbp_text);
//**********
//*****addition for attaching files on 20/01/2004
int totalFiles = fileNames.length;
String filenm;
MimeBodyPart mbp55;
DataSource src;
for(int i=0;i<totalFiles;i++)
{
filenm = fileNames;
System.out.println("FILE NAME IN SEND: "+filenm);
mbp55 = new MimeBodyPart();
src = new FileDataSource(filenm);
mbp55.setDataHandler(new DataHandler(src));
filenm = extractFileName(filenm);
mbp55.setFileName(filenm);
mp.addBodyPart(mbp55);
System.out.println("FILE ATTACHED");
}
System.out.println("After the attaching");
//content gif file for the html mail
mbp55 = new MimeBodyPart();
String ds = prop.getProperty("HTML_PATH")+prop.getProperty("HTML_IMAGE");
src = new FileDataSource(ds);
mbp55.setDataHandler(new DataHandler(src));
mbp55.setFileName(prop.getProperty("HTML_IMAGE"));
mbp55.setHeader("Content-ID","><banner>");
mp.addBodyPart(mbp55);
m = new MimeBodyPart();
m.setContent(mp);
}
System.out.println("returning from the create mail");
return m;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unexpected error: " + e.toString());
}
}
/**
*Signing the emails
*@param MimeBodypart
*@returnMimeMultipart Required format in the SendMail() method.
*/
private MimeMultipart sign(MimeBodyPart msg) {
try {
ArrayListcertList = new ArrayList();
certList.add(senderCert);
//
// create a CertStore containing the certificates we want carried
// in the signature
//
CertStorecertsAndcrls = CertStore.getInstance(
"Collection",
new CollectionCertStoreParameters(certList), "BC");
//
// create some smime capabilities in case someone wants to respond
//
ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
SMIMECapabilityVectorcaps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
// create the generator for creating an smime/signed message
//
SMIMESignedGenerator gen = new SMIMESignedGenerator();
// add a signer to the generator - this confirms the use of SHA1.The encryption algorithm
// used is taken from the key - RSA with PKCS1Padding
//
System.out.println(" Private Key :"+senderKey);
System.out.println("Sender Cert :"+senderCert);
gen.addSigner(senderKey, senderCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
//
// pool of certs and cerls (if any) to go with the signature
//
gen.addCertificatesAndCRLs(certsAndcrls);
MimeMultipart mm = gen.generate(msg, "BC");
return mm;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*Encryption of the email after signing.
*@param MimeMessage - The transformed package after the signing process.
*@returnMimeBodyPart Required format in the SendMail() method.
*/
private MimeBodyPart encrypt(MimeMessage msg) {
try {
SMIMEEnvelopedGenerator genE = new SMIMEEnvelopedGenerator();
genE.addKeyTransRecipient(rcptCert);
MessageDigest dig = MessageDigest.getInstance("SHA1","BC");
dig.update(rcptCert.getPublicKey().getEncoded());
genE.addKeyTransRecipient(rcptCert.getPublicKey(),dig.digest());
MimeBodyPart mpp = genE.generate(msg,SMIMEEnvelopedGenerator.DES_EDE3_CBC,"BC");
return mpp;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*This method extracts the private key from the provided key.
*@param keyFile - Key file from which the private key has to be extracted.
*@paramalias- Alias for the key
*@returnPrivateKey Extracted private key
*/
private PrivateKey getKey(String keyFile, String alias) {
try {
FileInputStream fis = new FileInputStream(keyFile);
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] pw = prop.getProperty("PRV_KEY_PASSWD").toCharArray();
System.out.println("loading keystore");
ks.load(fis, pw);
char[] pw2 = prop.getProperty("PRV_KEY_PASSWD").toCharArray();
return (PrivateKey) ks.getKey(alias, pw2);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*
private PrivateKey getKey(String keyFile,String alias) {
try { //get keystore
KeyStore ks = KeyStore.getInstance("PKCS12");
char [] password = alias.toCharArray();
ks.load(new FileInputStream(keyFile), password);
System.out.println("OK");
PrivateKey privatekey = null;
Enumeration en = ks.aliases();
String ALIAS = "";
Vector vectaliases = new Vector();
while (en.hasMoreElements())
vectaliases.add(en.nextElement());
String[] aliases = (String []) (vectaliases.toArray(new String[0]));
for (int i = 0; i < aliases.length; i++)
if (ks.isKeyEntry(aliases))
{
ALIAS = aliases;
break;
}
privatekey = (PrivateKey)ks.getKey(ALIAS, password);
System.out.println("alias :["+ALIAS+"] length:"+ALIAS.length());
System.out.println("Private Key :"+privatekey.toString());
return privatekey;
}catch(Exception exp){
exp.printStackTrace();
}
return null;
} */
/**
*This method extracts the certificate from the certstore.
*@param certFile - Certificate File
*@paramrcptEmail- Email of the Receipient
*@returnX509Certificate Certificate.
*/
private X509Certificate getCert(String certFile,String rcptEmail) {
try {
FileInputStream fis = new FileInputStream(certFile);
DataInputStream dis = new DataInputStream(fis);
byte[] data = new byte[dis.available()];
dis.readFully(data);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
CertificateFactory fact = CertificateFactory.getInstance("X509");
X509Certificate cert =
(X509Certificate) fact.generateCertificate(bais);
return cert;
}
catch (FileNotFoundException e) {
e.printStackTrace();
noCert=true;
return null;
}
catch(NullPointerException e)
{
e.printStackTrace();
System.out.println("NULL POINTER");
noCert=true;
return null;
}
catch(Exception e)
{
e.printStackTrace();
noCert=true;
return null;
}
}
public String extractFileName(String filename)
{
String temp="";
String fl;
for (int i = 0; i<filename.length(); i++)
{
fl = String.valueOf(filename.charAt(i));
if(fl.equals("/"))
{
temp="";
}
else
{
temp = temp+fl;
}
}
return temp;
}
public String getDate()
{
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyy-MM-dd--HH-mm-ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String today = sdf.format(cal.getTime());
return today;
}
public void setHtml(String data)
{
html1=data;
html2=html3=html4=html5="";
}
String getHtmlDate()
{
return(DateFormat.getDateInstance(DateFormat.FULL).format(new Date()));
}
}>