Send Email With Attachment in Java
public boolean sendEmailWithAttachment() {
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp host address");
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props, new MailAuthenticator());
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress address = new InternetAddress(to);
msg.setRecipient(Message.RecipientType.TO, address);
msg.setSubject("Subject");
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent("Body Text", "text/html");
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
//System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
return false;
}
}
return true;
}
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp host address");
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props, new MailAuthenticator());
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress address = new InternetAddress(to);
msg.setRecipient(Message.RecipientType.TO, address);
msg.setSubject("Subject");
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent("Body Text", "text/html");
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
//System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
return false;
}
}
return true;
}
Comments
Post a Comment