List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:pt.webdetails.cdv.notifications.EmailOutlet.java
private Multipart getMultipartBody(final Session session, final Alert alert) throws MessagingException, IOException { // if we have a mimeMessage, use it. Otherwise, build one with what we have // We can have both a messageHtml and messageText. Build according to it MimeMultipart parentMultipart = new MimeMultipart(); MimeBodyPart htmlBodyPart = null, textBodyPart = null; final String content = getMessageBody(alert); textBodyPart = new MimeBodyPart(); textBodyPart.setContent(content, "text/plain; charset=" + CharsetHelper.getEncoding()); final MimeMultipart textMultipart = new MimeMultipart(); textMultipart.addBodyPart(textBodyPart); parentMultipart = textMultipart;/*w w w . ja v a 2 s . co m*/ // We have both text and html? Encapsulate it in a multipart/alternative if (htmlBodyPart != null && textBodyPart != null) { final MimeMultipart alternative = new MimeMultipart("alternative"); alternative.addBodyPart(textBodyPart); alternative.addBodyPart(htmlBodyPart); parentMultipart = alternative; } return parentMultipart; }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {/*from w w w . j a va 2s. co m*/ Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); Subscription obj = container.getObj(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s //maybe nice to use a template rather then sending raw xml. org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription(); MappingModelToApi.mapSubscription(obj, api); String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey())); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:com.cosmicpush.plugins.smtp.EmailMessage.java
/** * @param session the applications current session. * @throws EmailMessageException in response to any other type of exception. *//* w ww. jav a2 s. c om*/ @SuppressWarnings({ "ConstantConditions" }) protected void send(Session session) throws EmailMessageException { try { // create a message MimeMessage msg = new MimeMessage(session); //set some of the basic attributes. msg.setFrom(fromAddress); msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses)); msg.setSubject(subject); msg.setSentDate(new Date()); if (replyToAddress.isEmpty() == false) { msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress)); } // create the Multipart and add set it as the content of the message Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // create and fill the HTML part of the messgae if it exists if (html != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(html, "UTF-8", "html"); multipart.addBodyPart(bodyPart); } // create and fill the text part of the messgae if it exists if (text != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text, "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } if (html == null && text == null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("", "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } // remove any nulls from the list of attachments. while (attachments.remove(null)) { /* keep going */ } // Attach any files that we have, making sure that they exist first for (File file : attachments) { if (file.exists() == false) { throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist."); } else { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(file); multipart.addBodyPart(attachmentPart); } } // send the message Transport.send(msg); } catch (EmailMessageException ex) { throw ex; } catch (Exception ex) { throw new EmailMessageException("Exception sending email\n" + toString(), ex); } }
From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java
private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal) throws MessagingException { if (appockMail.getBonLivraison() == null) { msg.setContent(contenuFinal, "text/html; charset=utf-8"); } else {//from www . j av a 2 s . co m BonLivraison bonLivraison = appockMail.getBonLivraison(); Multipart multipart = new MimeMultipart(); BodyPart attachmentBodyPart = new MimeBodyPart(); File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison()); ByteArrayDataSource bds = null; try { bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()), bonLivraison.getMimeType().getLibelle()); } catch (IOException e) { e.printStackTrace(); } attachmentBodyPart.setDataHandler(new DataHandler(bds)); attachmentBodyPart.setFileName(bonLivraison.getNomFichier()); multipart.addBodyPart(attachmentBodyPart); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8"); multipart.addBodyPart(htmlBodyPart); msg.setContent(multipart); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from w w w . jav a 2 s . c o m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry/*from www. j a v a 2 s .co m*/ * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods, String audio) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();//from w ww.j a v a 2 s .c o m MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(imageds)); messageBodyPart.setFileName(image); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(audiods)); messageBodyPart.setFileName(audio); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java
private static void setFileAsAttachment(Message msg, String message, File file) throws MessagingException { MimeBodyPart p1 = new MimeBodyPart(); p1.setText(message);//from w w w . jav a 2s . c o m // Create second part MimeBodyPart p2 = new MimeBodyPart(); // Put a file in the second part FileDataSource fds = new FileDataSource(file); p2.setDataHandler(new DataHandler(fds)); p2.setFileName(fds.getName()); // Create the Multipart. Add BodyParts to it. Multipart mp = new MimeMultipart(); mp.addBodyPart(p1); mp.addBodyPart(p2); // Set Multipart as the message's content msg.setContent(mp); }
From source file:com.enonic.esl.net.Mail.java
/** * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance. * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p> */// w w w . j a v a 2 s .c o m public void send() throws ESLException { // smtp server Properties smtpProperties = new Properties(); if (smtpHost != null) { smtpProperties.put("mail.smtp.host", smtpHost); System.setProperty("mail.smtp.host", smtpHost); } else { smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST); System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST); } Session session = Session.getDefaultInstance(smtpProperties, null); try { // create message Message msg = new MimeMessage(session); // set from address InternetAddress addressFrom = new InternetAddress(); if (from_email != null) { addressFrom.setAddress(from_email); } if (from_name != null) { addressFrom.setPersonal(from_name, ENCODING); } ((MimeMessage) msg).setFrom(addressFrom); if ((to.size() == 0 && bcc.size() == 0) || subject == null || (message == null && htmlMessage == null)) { LOG.error("Missing data. Unable to send mail."); throw new ESLException("Missing data. Unable to send mail."); } // set to: for (int i = 0; i < to.size(); ++i) { String[] recipient = to.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo); } // set bcc: for (int i = 0; i < bcc.size(); ++i) { String[] recipient = bcc.get(i); InternetAddress addressTo = null; try { addressTo = new InternetAddress(recipient[1]); } catch (Exception e) { System.err.println("exception on address: " + recipient[1]); continue; } if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo); } // set cc: for (int i = 0; i < cc.size(); ++i) { String[] recipient = cc.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo); } // Setting subject and content type ((MimeMessage) msg).setSubject(subject, ENCODING); if (message != null) { message = RegexpUtil.substituteAll("\\\\n", "\n", message); } // if there are any attachments, treat this as a multipart message. if (attachments.size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (message != null) { ((MimeBodyPart) messageBodyPart).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // add all attachments for (int i = 0; i < attachments.size(); ++i) { Object obj = attachments.get(i); if (obj instanceof String) { System.err.println("attachment is String"); messageBodyPart = new MimeBodyPart(); ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof File) { messageBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource((File) obj); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof FileItem) { FileItem fileItem = (FileItem) obj; messageBodyPart = new MimeBodyPart(); FileItemDataSource fds = new FileItemDataSource(fileItem); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else { // byte array messageBodyPart = new MimeBodyPart(); ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); } else { if (message != null) { ((MimeMessage) msg).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeMessage) msg).setDataHandler(dataHandler); } } // send message Transport.send(msg); } catch (AddressException e) { String MESSAGE_30 = "Error in email address: " + e.getMessage(); LOG.warn(MESSAGE_30); throw new ESLException(MESSAGE_30, e); } catch (UnsupportedEncodingException e) { String MESSAGE_40 = "Unsupported encoding: " + e.getMessage(); LOG.error(MESSAGE_40, e); throw new ESLException(MESSAGE_40, e); } catch (SendFailedException sfe) { Throwable t = null; Exception e = sfe.getNextException(); while (e != null) { t = e; if (t instanceof SendFailedException) { e = ((SendFailedException) e).getNextException(); } else { e = null; } } if (t != null) { String MESSAGE_50 = "Error sending mail: " + t.getMessage(); throw new ESLException(MESSAGE_50, t); } else { String MESSAGE_50 = "Error sending mail: " + sfe.getMessage(); throw new ESLException(MESSAGE_50, sfe); } } catch (MessagingException e) { String MESSAGE_50 = "Error sending mail: " + e.getMessage(); LOG.error(MESSAGE_50, e); throw new ESLException(MESSAGE_50, e); } }
From source file:org.nuxeo.ecm.automation.core.mail.Composer.java
public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType, List<Blob> attachments) throws TemplateException, IOException, MessagingException { if (textType == null) { textType = "plain"; }//from w w w . j a v a 2 s . com Mailer.Message msg = mailer.newMessage(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); String result = render(templateContent, ctx); body.setText(result, "UTF-8", textType); mp.addBodyPart(body); for (Blob blob : attachments) { MimeBodyPart a = new MimeBodyPart(); a.setDataHandler(new DataHandler(new BlobDataSource(blob))); a.setFileName(blob.getFilename()); mp.addBodyPart(a); } msg.setContent(mp); return msg; }