/** * Title MimeMessage * @Description Create a email. * @param session,sendMail and receiveMail. * @return MimeMessage * @throws MessagingException * @throws IOException * @date Feb 21, 2019-11:02:10 AM * */ publicstatic MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws MessagingException, IOException {
// 1: Create a email. MimeMessage message = new MimeMessage(session); // 2: From : addresser. message.setFrom(new InternetAddress(sendMail, "Java Program", "UTF-8")); // 3: To : recipients. message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "Program", "UTF-8")); // 4: Subject : The email theme. message.setSubject(MY_EMAIL_SUBJECT, "UTF-8");
/* * Create the content of the email as followed . */ // 5: Create the node of image. MimeBodyPart image = new MimeBodyPart(); DataHandler dataHandler = new DataHandler(new FileDataSource("resource/Cute_pig.jpg"));// read the local file. image.setDataHandler(dataHandler);// Add the data of image to the node. image.setContentID("image_Cut_pig_id");// Set a unique number for the node and his ID is referenced in the text "node".
// 6: Create the node of text. MimeBodyPart text = new MimeBodyPart(); // You can actually add web images by HTTP links as well. text.setContent(MY_EMAIL_CONTENT, "text/html;charset=UTF-8");
// 7: Combine text and image "nodes" into a hybrid "node". MimeMultipart mm_text_image = new MimeMultipart(); mm_text_image.addBodyPart(text); mm_text_image.addBodyPart(image); mm_text_image.setSubType("related");// incidence relation.
// 8: Encapsulate the text + image hybrid "node" as a normal "node". Attention: // The "Content" that is eventually added to the emailis a Multipart composed of "bodyparts". MimeBodyPart text_image = new MimeBodyPart(); text_image.setContent(mm_text_image);
// 9: Create the node of attachment. MimeBodyPart attachment = new MimeBodyPart(); DataHandler dataHandler2 = new DataHandler(new FileDataSource("resource/Love_Yourself.mp3")); attachment.setDataHandler(dataHandler2); // Set the file name of the attachment (encoding required). attachment.setFileName(MimeUtility.encodeText(dataHandler2.getName()));
// 10: Set the relationship between ('text' + 'image') and the // 'attachment'.(compositing a large mixed "node"/Multipart). MimeMultipart mm_text_image_att = new MimeMultipart(); mm_text_image_att.addBodyPart(text_image);// reference: 8. mm_text_image_att.addBodyPart(attachment); mm_text_image_att.setSubType("mixed");// mixed relations.
// 11: Set the relationship for the entire email. (add the final mixed "node" as // the content of the email to the message object). message.setContent(mm_text_image_att);
// 12: Set the date. message.setSentDate(new Date()); // 13: Save the setting. message.saveChanges();