Hi,
I'm using javamail 1.3, and trying to write a util that sends an email with a list of attachments.
When the email goes through, it puts the attachments in the message body (inline). I've tried a number of variations, including the commented out lines. Any assistance would be most welcome.
Cheers,
Tim
public static void sendEmailWithFileAttachment(
String p_emailList, String p_fromUser, String p_subject, String p_msg, String[] _attachFileName) {
try {
if (p_emailList == null) return;
StringTokenizer emailAddresses = new StringTokenizer(p_emailList);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
String smtpServer = System.getProperty("mail.host");
if (smtpServer != null)
props.setProperty("mail.host", smtpServer);
else {
props.setProperty("mail.host", SEMPRA_DEFAULT_SMTP_SERVER);
smtpServer = SEMPRA_DEFAULT_SMTP_SERVER;
}
if (p_fromUser != null) props.setProperty("mail.user", p_fromUser);
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(p_subject);
Multipart multiPart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
//messageBodyPart.setText(p_msg);
messageBodyPart.setContent(p_msg, "text/plain");
multiPart.addBodyPart(messageBodyPart);
if (_attachFileName != null) {
for (int i = 0; i < _attachFileName.length; i++) {
BodyPart attachmentBodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(_attachFileName[i]);
File file = new File(_attachFileName[i]);
if (file.isFile()) {
int length = (int)file.length();
byte[] fileData = new byte[length];
try {
InputStream fis = new FileInputStream(file);
int ii = fis.read(fileData);
attachmentBodyPart.setDataHandler(new DataHandler(fds));
//DataSource source = new ByteArrayDataSource(fis, "application/x-any");
//attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(new File(_attachFileName[i]).getName());
//attachmentBodyPart.setDisposition(Part.ATTACHMENT);
//attachmentBodyPart.setHeader("content-type","application/pdf");
multiPart.addBodyPart(attachmentBodyPart);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
message.setContent(multiPart);
//System.out.println("addresses: "+p_emailList);
while (emailAddresses.hasMoreTokens()) {
String toAddress = emailAddresses.nextToken(LIST_DELIMITER);
//System.out.println("sending email to "+toAddress);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
}
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
catch (MessagingException e) {
System.out.println("Failed sending email " + e.getMessage());
}
}