Here is a example:
private static void notify(String subject, String text,
File attachment, String from, String to) throws Exception {
Context context = new InitialContext();
Session sess = (Session)context.lookup("java:comp/env/mail/session");
MimeMessage message = new MimeMessage(sess);
message.setSubject(subject, "UTF-8");
if (attachment == null) {
message.setText(text, "UTF-8");
} else {
MimeMultipart mp = null;
MimeBodyPart part1 = new MimeBodyPart();
part1.setText(text, "UTF-8");
MimeBodyPart part2 = new MimeBodyPart();
part2.setDataHandler(new DataHandler(new FileDataSource(attachement)));
part2.setFileName(file.getName());
mp = new MimeMultipart();
mp.addBodyPart(part1);
mp.addBodyPart(part2);
message.setContent(mp);
}
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(message);
}
In this example, a FileDataSource is used, which means that the attachment must first be saved as a file.
I sometimes use a home-brewed MemoryDataSource instead. Here is the code:
package com.lagalerie.mail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
public class MemoryDataSource implements DataSource {
private String name;
private String contentType;
private byte content[] = {};
public MemoryDataSource(String name, String contentType) {
this.name = name;
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(content);
}
public String getName() {
return name;
}
public OutputStream getOutputStream() {
return new ByteArrayOutputStream() {
@Override
public void close() {
content = toByteArray();
}
};
}
}