Hi I've the following code for sending
java mail with attachment. Its sending the mail but not attaching the file. Please could someone help. Thanks
/* Bean Properties */
private
String to = "mail@xxx.com";
private String from = null;
private String subject = null;
private String message = null;
private File attach =null;
public static Properties props = null;
public static Session session = null;
static {
/*Setting Properties for STMP host */
props = System.getProperties();
props.put("mail.smtp.host", "mail.xxx.com");
session = Session.getDefaultInstance(props, null);
}
/* Setter Methods */
public void setTo(String to) {
this.to = to;
}
public void setFrom(String from) {
this.from = from;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setMessage(String message) {
this.message = message;
}
public void setAttach(File attach) {
this.attach = attach;
}
/* Sends Email */
public void sendMail() throws Exception {
if(!this.everythingIsSet())
throw new Exception("Could not send email.");
try {
MimeMessage message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(this.to));
message.setFrom(new InternetAddress(this.from));
message.setSubject(this.subject);
message.setText(this.message);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(this.message);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
javax.activation.DataSource fds = new FileDataSource(attach);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
message.setContent(mp);
message.setText(this.message);
Transport.send(message);
}
catch (MessagingException e) {
throw new Exception(e.getMessage());
}
}