Hi,
Try the following code
[i]
/**
* This method sends the mail after authentication
* @param subject subject of the mail
* @param message massege to send in the mail
* @param attachments mail attachements
* @param from from address in the mail
*/
public void sendMail( String subject, String message,String attachments[], String from){
// boolean debug = false;
try{
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
// Get session
Session session = Session.getDefaultInstance(props,auth);
//Session session = Session.getDefaultInstance(props,null);
session.setDebug(true);
// Define message
MimeMessage messageObj = new MimeMessage(session);
// Set From and To addresses
messageObj.setFrom(new InternetAddress(from));
/*InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
messageObj.setRecipients(Message.RecipientType.TO, addressTo);
messageObj.setSubject(subject);
*/
InternetAddress[] addressTo = new InternetAddress[1];
addressTo[0] = new InternetAddress(To);
messageObj.setRecipients(Message.RecipientType.TO, addressTo);
messageObj.setSubject(subject);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill message
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//Attachments
messageBodyPart = new MimeBodyPart();
for (int i = 0; i < attachments.length; i++) {
DataSource source = new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachments);
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
messageObj.setContent(multipart);
// Send the message
Transport.send(messageObj);
}catch(Exception e){
e.printStackTrace();
}
}
Regards,
Rakesh
|