To send html file I have used below code in my project.
final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userID, userPass);
}
});
try {
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
message.setSubject("Hello, this is a test mail..");
Multipart multipart = new MimeMultipart();
String fileName = "fileName";
addAttachment(multipart, fileName);
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("No need to reply.");
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email successfully sent to: " + emailTo);
} catch (MessagingException e) {
e.printStackTrace();
}
private static void addAttachment(Multipart multipart, String fileName){
DataSource source = null;
File f = new File("filepath" +"/"+ fileName);
if(f.exists() && !f.isDirectory()) {
source = new FileDataSource("filepath" +"/"+ fileName);
BodyPart messageBodyPart = new MimeBodyPart();
try {
messageBodyPart.setHeader("Content-Type", "text/html");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}