// Common variablesString host = "your_smtp_server";String from = "from_address";String to = "to_address"; // Set propertiesProperties props = new Properties();props.put("mail.smtp.host", host);props.put("mail.debug", "true"); // Get sessionSession session = Session.getInstance(props); try { // Instantiate a message Message msg = new MimeMessage(session); // Set the FROM message msg.setFrom(new InternetAddress(from)); // The recipients can be more than one so we use an array but you can // use 'new InternetAddress(to)' for only one address. InternetAddress[] address = {new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO, address); // Set the message subject and date we sent it. msg.setSubject("Email from JavaMail test"); msg.setSentDate(new Date()); // Set message content msg.setText("This is the text for this simple demo using JavaMail."); // Send the message Transport.send(msg);}catch (MessagingException mex) { mex.printStackTrace();}
One can use the following to set the content of the message and declare its Mime type instead of setting only the text:
1 msg.setContent("This is the text for this simple demo using JavaMail.", "text/plain");
Multipart Messages
Sending messages that contain for example, HTML and rich text. Message composed of different parts.
123456789101112131415161718 ...// Here create two parts and set as message contect// Create and fill first partMimeBodyPart part1 = new MimeBodyPart();part1.setText("This is part one of this multipart message."); // Create and fill second partMimeBodyPart part2 = new MimeBodyPart();part2.setText("This is part two of this multipart message."); // Create the Multipart.Multipart mp = new MimeMultipart();mp.addBodyPart(part1);mp.addBodyPart(part2); // Set the message's contentmsg.setContent(mp);...
Sending Attachments
123456789101112131415 ...// Create a new part for the attached fileMimeBodyPart part3 = new MimeBodyPart(); // Put a file in the second partFileDataSource fds = new FileDataSource("THE_FILE_NAME");part3.setDataHandler(new DataHandler(fds));part3.setFileName(fds.getName()); // 'mp' is the previously created 'MimeMultipart' objectmp.addBodyPart(part3); // 'msg' is the previously created 'Message' objectmsg.setContent(mp);...
HTML message
1234 ...MimeBodyPart htmlPart = new MimeBodyPart();htmlPart.setContent("
This is a sample HTML part
", "text/html");...This is a sample HTML part with an attached image
" + "Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology