Thursday 15 May 2014

Sending Email with Attachments


//Java program for sending Email

public class SendEmail{
public static void sendEmailWithAttachments(String host, String port,final String userName, final String password, String toAddress,String subject, String 
message, String[] attachFiles)throws AddressException, MessagingException {

// sets SMTP server properties

try {
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);

// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);

// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());

// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");

// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// adds attachments
if (attachFiles != null && attachFiles.length > 0) {

MimeBodyPart attachPart = null;
try{
for(int i=0;i<attachFiles.length;i++){
attachPart=new MimeBodyPart();
System.out.println(attachFiles[i]);
attachPart.attachFile(attachFiles[i]);
multipart.addBodyPart(attachPart);
}

     }
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);

} catch(javax.mail.MessagingException me) {
System.out.println("Email Not Sent ");
me.printStackTrace();
}
System.out.println("Email sent.");

}

/**
*   * Test sending e-mail with attachments   
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your email address";
String password = "your password";
// message info
String mailTo = "reciepient email";
String subject = "send Email";
String message = "I have some attachments for you.";

// attachments
String attachFiles[] =new String[2]; //no of attachments
attachFiles[0] = "E:/src/names.xml";
attachFiles[1] = "E:/src/rose.png";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}

}
}

No comments:

Post a Comment