Java Mail with Attachment-Attachment file location not found
My code for sending email without attachment works fine. But when I try to
send an email wth attachment, I am getting an error message
'C:\Temp\test.txt (The system cannot find the file specified)' The code is
below: '
package com.ceridian.test;
import java.util.Properties;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class TestJavaMail {
/**
* @param args
*/
public static void main(String[] args) {
final String username = "from@gmail.com";
final String password = "xxxx";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("manojvtp@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("mvarghese@speech-soft.com"));
message.setSubject("Testing Subject 1");
message.setText("PFA");
//
Transport.send("manojvtp@gmail.com","mvarghese@speech-soft.com",
"Hi Kamran, how is going?" , ")");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:/Temp/test.txt";
// String fileName = "test.txt";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Do I need to set any ClassPATH or anything else to get the file attachment
working?
Thanks
No comments:
Post a Comment