Here is a method I wrote to do this on an SMTP server.
Its probably not that good as Im new to using multipart messages, but it works. The problem is that it will not attach any images included in the original page, not an issue in my case as there were no images in the report I wanted to send.
You should use the search bar to the left to find more code, most of what is in this method was found in these forums. Also there is a java mail forum which is better for this kind of question.
/**
* Method for sending multipart mail with HTML output as an attachment.
* Data is read in from a URL (JSP page) and attached to the mail, allowing reports to be mailed from the application
* @param fromthe mail address to be sent 'from'
* @param tothe destination mail address
* @param ccrecipients to be copied
* @param bccrecipients to be blind copied
* @parma subjectsubject of the mail
* @param contenttextual content of the mail
* @param urlthe url of the page to be attached
*/
public static void sendURL(String from, String to, String CC, String BCC, String subject, String content, URL url)
throws AddressException, MessagingException, Exception
{
String smtpHost = "127.0.0.1";
int smtpPort = 25;
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SimpleAuthenticator();
Session session = Session.getInstance(props, auth);
// Construct the message
Message msg = new MimeMessage(session);
msg.setHeader("Content-ID","text/html");
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
if (!CC.equals(""))
{
msg.setRecipient(Message.RecipientType.CC, new InternetAddress(CC));
}
if(!BCC.equals(""))
{
msg.setRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
}
msg.setSubject(subject);
DataSource message = new URLDataSource(url);
DataHandler handler = new DataHandler(message);
MimeBodyPart mbp = new MimeBodyPart();
mbp.setHeader("Content-ID","text/html");
mbp.setDataHandler(handler);
mbp.setFileName("test.html");
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setHeader("Content-ID","text/html");
mbp2.setText(content);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
mp.addBodyPart(mbp2);
msg.setContent(mp);
msg.saveChanges();
// Send the message
Transport.send(msg);
}
Should mention
Authenticator auth = new SimpleAuthenticator();
is a class you will need to create yourself if your server requries authentication.
If you dont need authentication then remove this and other relevant lines.
To find out how to create such a class search the forums, there are examples.