I have implemented simple e-mail service which I want to extend with file attachment. This is the code so far:
private String sendFromGMail(String from, String pass, String[] to, String subject, String body)
{
String status;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++)
{
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae)
{
ae.printStackTrace();
return status = "Cannot send Message!";
}
catch (MessagingException me)
{
me.printStackTrace();
return status = "Cannot send Message!";
}
return status = "Message is send!";
}
As attachment I would like to use this object:
private Part file;
I tried to implement it this way using this code:
private Part file;
........
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
// String file = "path of file to be attached";
// String fileName = "attachmentName";
DataSource source = new FileDataSource((File) file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
I get this error:
serverError: class javax.faces.el.EvaluationException org.apache.catalina.core.ApplicationPart cannot be cast to java.io.File
Can you help me to solve the problem?
Replace:
// String file = "..."; DataSource source = new FileDataSource((File) file);
with:
String pathToFile = "..."; DataSource source = new FileDataSource(new File(pathTofile));