List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this method * will generate an email message that includes subject, message and * attachments to the recipient list. You can use the convenience * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i> * and <i>createAttachmentList()</i> for parameter building assistance. * * @param aFromAddress Source email address. * @param aRecipientList List of recipient email addresses. * @param aSubject Subject of the email message. * @param aMessage Messsage./*w ww .j a va2 s. c om*/ * @param anAttachmentFiles List of file attachments or <i>null</i> for none. * * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a> * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a> * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage, ArrayList<String> anAttachmentFiles) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0) && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); Message mimeMessage = new MimeMessage(mMailSession); internetAddressFrom = new InternetAddress(aFromAddress); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); for (String mailAddressTo : aRecipientList) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } mimeMessage.setSubject(aSubject); // The following logic create a multi-part message and adds the attachment to it. BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(aMessage); // messageBodyPart.setContent(aMessage, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) { for (String pathFileName : anAttachmentFiles) { File attachmentFile = new File(pathFileName); if (attachmentFile.exists()) { messageBodyPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(pathFileName); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); multipart.addBodyPart(messageBodyPart); } } appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage)); } else appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); mimeMessage.setContent(multipart); Transport.send(mimeMessage); } else throw new NSException("Valid from, recipient, subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;/* www. ja va 2s . c om*/ } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {//from w w w. j ava 2 s .c o 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.tdclighthouse.commons.mail.util.MailClient.java
protected void addAtachments(String[] attachments, Multipart multipart) throws MessagingException, AddressException { for (int i = 0; i < attachments.length; i++) { String filename = attachments[i]; MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // use a JAF FileDataSource as it does MIME type detection DataSource source = new FileDataSource(filename); attachmentBodyPart.setDataHandler(new DataHandler(source)); // assume that the filename you want to send is the same as the // actual file name - could alter this to remove the file path attachmentBodyPart.setFileName(filename); // add the attachment multipart.addBodyPart(attachmentBodyPart); }/*w w w .ja v a2 s.c om*/ }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
@Override public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body, List<NodeRef> attachments, boolean html) throws Exception { EmailConfig config = getConfig();/*from w w w .j a v a 2 s . c o m*/ EmailProvider provider = getEmailProvider(config.getProviderId()); Properties props = System.getProperties(); String prefix = "mail." + provider.getOutgoingProto() + "."; props.put(prefix + "host", provider.getOutgoingServer()); props.put(prefix + "port", provider.getOutgoingPort()); props.put(prefix + "auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName())); if (to != null) { InternetAddress[] recipients = new InternetAddress[to.size()]; for (int i = 0; i < to.size(); i++) recipients[i] = new InternetAddress(to.get(i)); msg.setRecipients(Message.RecipientType.TO, recipients); } if (cc != null) { InternetAddress[] recipients = new InternetAddress[cc.size()]; for (int i = 0; i < cc.size(); i++) recipients[i] = new InternetAddress(cc.get(i)); msg.setRecipients(Message.RecipientType.CC, recipients); } if (bcc != null) { InternetAddress[] recipients = new InternetAddress[bcc.size()]; for (int i = 0; i < bcc.size(); i++) recipients[i] = new InternetAddress(bcc.get(i)); msg.setRecipients(Message.RecipientType.BCC, recipients); } msg.setSubject(subject); msg.setHeader("X-Mailer", "Alvex Emailer"); msg.setSentDate(new Date()); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); if (body != null) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body, "utf-8", html ? "html" : "plain"); multipart.addBodyPart(messageBodyPart); } if (attachments != null) for (NodeRef att : attachments) { messageBodyPart = new MimeBodyPart(); String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME); messageBodyPart .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService))); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto()); t.connect(config.getUsername(), config.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java
/** * Mail the email formatted using the given templates * @param toEmailAddresses List of email addresses to which emails should be sent. White space delimited. * @param fromEmailAddress fromEmailAddress * @param subject subject of the email/* w ww. ja v a2 s. co m*/ * @param context context to set the values from for the template * @param textTemplateFilename textTemplateFilename * @param htmlTemplateFilename htmlTemplateFilename */ public void mail(final String toEmailAddresses, final String fromEmailAddress, final String subject, final Map<String, Object> context, final String textTemplateFilename, final String htmlTemplateFilename) { final StringTokenizer emailTokens = new StringTokenizer(toEmailAddresses); while (emailTokens.hasMoreTokens()) { final String toEmailAddress = emailTokens.nextToken(); final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws MessagingException, IOException { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, configuration.getDefaultEncoding()); message.setTo(new InternetAddress(toEmailAddress)); message.setFrom(new InternetAddress(fromEmailAddress, (String) context.get(USER_NAME_KEY))); message.setSubject(subject); // Create a "text" Multipart message final Multipart mp = createPartForMultipart(textTemplateFilename, context, "alternative", MIME_TYPE_TEXT_PLAIN + "; charset=" + configuration.getDefaultEncoding()); // Create a "HTML" Multipart message final Multipart htmlContent = createPartForMultipart(htmlTemplateFilename, context, "related", MIME_TYPE_TEXT_HTML + "; charset=" + configuration.getDefaultEncoding()); final BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent); mp.addBodyPart(htmlPart); mimeMessage.setContent(mp); } }; mailSender.send(preparator); if (log.isDebugEnabled()) { log.debug("Mail sent to:" + toEmailAddress); } } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/* www . j ava2s . c om*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /*from w w w . j av a2 s . co m*/ * @param to - to email address * @param docType - String value for the attached document type * @param subject - Subject for the email * @param instructions - email body * @param content - content to be sent as attachment * @return MimeMessage instance */ public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content, String metadataXMl, String title, String indexBodyToken, String readmeToken) { final MimeMessage msg = mailSender.createMimeMessage(); UUID uniqueID = UUID.randomUUID(); tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID); try { msg.setFrom(new InternetAddress(getFrom())); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // The readable part final MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(instructions); mbp1.setHeader("Content-Type", "text/plain"); // The notification final MimeBodyPart mbp2 = new MimeBodyPart(); final String contentType = "application/xml; charset=UTF-8"; String extension; // HL7 messages should be a txt file, otherwise xml if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) { extension = TXT_EXT; } else { extension = XML_EXT; } final String fileName = docType + UUID.randomUUID() + extension; // final DataSource ds = new AttachmentDS(fileName, content, contentType); // mbp2.setDataHandler(new DataHandler(ds)); /******** START NHIN COMPLIANCE CHANGES *****/ boolean isTempZipFolderCreated = tempZipFolder.mkdirs(); if (!isTempZipFolderCreated) { LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); } String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM")); String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT")); indexFileString = StringUtils.replace(indexFileString, "@document_title@", title); indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString); readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString); // move template files & replace tokens // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false); // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false); // create sub-directories String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01"; File nhinSubDirectory = new File(nhinSubDirectoryPath); boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs(); if (!isNhinSubDirectoryCreated) { LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); } FileOutputStream metadataStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/METADATA.XML")); metadataStream.write(metadataXMl.getBytes()); metadataStream.flush(); metadataStream.close(); FileOutputStream documentStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/DOCUMENT" + extension)); documentStream.write(content.getBytes()); documentStream.flush(); documentStream.close(); String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP"; byte[] buffer = new byte[1024]; // FileOutputStream fos = new FileOutputStream(zipFile); // ZipOutputStream zos = new ZipOutputStream(fos); List<String> fileList = generateFileList(tempZipFolder); ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size()); ZipOutputStream zos = new ZipOutputStream(bout); // LOG.info("File List size: "+fileList.size()); for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); // remember close it zos.close(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); mbp2.setDataHandler(new DataHandler(source)); mbp2.setFileName(docType + ".ZIP"); /******** END NHIN COMPLIANCE CHANGES *****/ // mbp2.setFileName(fileName); // mbp2.setHeader("Content-Type", contentType); final Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.setSentDate(new Date()); // FileUtils.deleteDirectory(tempZipFolder); } catch (AddressException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (MessagingException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (IOException e) { LOG.error(e.getMessage()); throw new ApplicationRuntimeException(e.getMessage()); } finally { //reset filelist contents fileList = new ArrayList<String>(); } return msg; }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
protected void fillContent(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String text = getTemplate().getText(); String html = getTemplate().getHtml(); List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates(); try {/* www . java 2s .c om*/ if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p); // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(execution, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(execution, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(execution, multipart); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(execution, text, session); email.setText(text); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//from www . j a va 2s . co m * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); final Session session = Session.getInstance(props, null); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }