List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {/*from w w w.jav a 2 s .c om*/ // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }//from w ww . j a va2s . c om Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:org.wandora.piccolo.actions.SendEmail.java
public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Application application) {/*w ww . j a va2s . c om*/ try { Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (subject != null) message.setSubject(subject); if (from != null) message.setFrom(new InternetAddress(from)); Vector<String> recipients = new Vector<String>(); if (recipient != null) { String[] rs = recipient.split(","); String r = null; for (int i = 0; i < rs.length; i++) { r = rs[i]; if (r != null) recipients.add(r); } } MimeMultipart multipart = new MimeMultipart(); Template template = application.getTemplate(emailTemplate, user); HashMap context = new HashMap(); context.put("request", request); context.put("message", message); context.put("recipients", recipients); context.put("emailhelper", new MailHelper()); context.put("multipart", multipart); context.putAll(application.getDefaultContext(user)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); template.process(context, baos); MimeBodyPart mimeBody = new MimeBodyPart(); mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType()); // mimeBody.setContent(baos.toByteArray(),template.getMimeType()); multipart.addBodyPart(mimeBody); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(smtpServer, smtpUser, smtpPass); Address[] recipientAddresses = new Address[recipients.size()]; for (int i = 0; i < recipientAddresses.length; i++) { recipientAddresses[i] = new InternetAddress(recipients.elementAt(i)); } transport.sendMessage(message, recipientAddresses); } catch (Exception e) { logger.writelog("WRN", e); } }
From source file:org.sigmah.server.mail.MailSenderImpl.java
@Override public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException { final String user = email.getAuthenticationUserName(); final String password = email.getAuthenticationPassword(); final Properties properties = new Properties(); properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL); properties.setProperty(MAIL_SMTP_HOST, email.getHostName()); properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort())); final StringBuilder toBuilder = new StringBuilder(); for (final String to : email.getToAddresses()) { if (toBuilder.length() > 0) { toBuilder.append(','); }/*from w ww.j av a 2 s . co m*/ toBuilder.append(to); } final StringBuilder ccBuilder = new StringBuilder(); if (email.getCcAddresses().length > 0) { for (final String cc : email.getCcAddresses()) { if (ccBuilder.length() > 0) { ccBuilder.append(','); } ccBuilder.append(cc); } } final Session session = javax.mail.Session.getInstance(properties); try { final DataSource attachment = new ByteArrayDataSource(fileStream, FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType()); final Transport transport = session.getTransport(); if (password != null) { transport.connect(user, password); } else { transport.connect(); } final MimeMessage message = new MimeMessage(session); // Configures the headers. message.setFrom(new InternetAddress(email.getFromAddress(), false)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false)); if (email.getCcAddresses().length > 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false)); } message.setSubject(email.getSubject(), email.getEncoding()); // Html body part. final MimeMultipart textMultipart = new MimeMultipart("alternative"); final MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\""); textMultipart.addBodyPart(htmlBodyPart); final MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(textMultipart); // Attachment body part. final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setFileName(fileName); attachmentPart.setDescription(fileName); // Mail multipart content. final MimeMultipart contentMultipart = new MimeMultipart("related"); contentMultipart.addBodyPart(textBodyPart); contentMultipart.addBodyPart(attachmentPart); message.setContent(contentMultipart); message.saveChanges(); // Sends the mail. transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException ex) { throw new EmailException( "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex); } catch (IOException ex) { throw new EmailException("An error occured while reading the attachment of an email.", ex); } catch (MessagingException ex) { throw new EmailException("An error occured while sending an email.", ex); } }
From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java
/** * @param runner//from ww w. j ava 2s . co m * @param resultDir * @throws MessagingException * @throws IOException */ public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setHeader("Content-Transfer-Encoding", "7bit"); // To mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo())); // From mimeMessage.setFrom(new InternetAddress(config.getFrom())); HashMap<String, Object> context = new HashMap<String, Object>(); context.put("result", runner.getResult() ? "passed" : "failed"); context.put("passedCount", new Integer(runner.getPassedCount())); context.put("failedCount", new Integer(runner.getFailedCount())); context.put("totalCount", new Integer(runner.getHtmlSuiteList().size())); context.put("startTime", new Date(runner.getStartTime())); context.put("endTime", new Date(runner.getEndTime())); context.put("htmlSuites", runner.getHtmlSuiteList()); // subject mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset()); // multipart message MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset()); content.addBodyPart(body); File resultArchive = createResultArchive(resultDir); MimeBodyPart attachmentFile = new MimeBodyPart(); attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive))); attachmentFile.setFileName(RESULT_ARCHIVE_FILE); content.addBodyPart(attachmentFile); mimeMessage.setContent(content); // send mail _send(mimeMessage); }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters, ParameterResolutionContext prc) throws SenderException, MessagingException, IOException { MyMimeMultipart mimeMultipart = new MyMimeMultipart("related"); String start = null;/*from ww w . j a v a2s .co m*/ if (StringUtils.isNotEmpty(getInputMessageParam())) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\""); start = "<" + getInputMessageParam() + ">"; mimeBodyPart.setContentID(start); ; mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value [" + message + "]"); } if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); String name = pv.getDefinition().getName(); if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { Object value = pv.getValue(); if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; String fileName = null; String sessionKey = pv.getDefinition().getSessionKey(); if (sessionKey != null) { fileName = (String) prc.getSession().get(sessionKey + "Name"); } MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(fileName); mimeBodyPart.setContentID("<" + name + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value + "] and name [" + fileName + "]"); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + name + "]"); } } else { String value = pv.asStringValue(""); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(value, "text/xml"); if (start == null) { start = "<" + name + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + name + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug( getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]"); } } } if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) { String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey()); if (StringUtils.isEmpty(multipartXml)) { log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty"); } else { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { throw new SenderException(getLogPrefix() + "error building multipart xml", e); } Collection parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]"); } else { int c = 0; Iterator iter = parts.iterator(); while (iter.hasNext()) { c++; Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partMimeType = partElement.getAttribute("mimeType"); String partSessionKey = partElement.getAttribute("sessionKey"); Object partObject = prc.getSession().get(partSessionKey); if (partObject instanceof FileInputStream) { FileInputStream fis = (FileInputStream) partObject; MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, (partMimeType == null ? "application/octet-stream" : partMimeType)); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(partName); mimeBodyPart.setContentID("<" + partName + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { String partValue = (String) prc.getSession().get(partSessionKey); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(partValue, "text/xml"); if (start == null) { start = "<" + partName + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + partName + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey + "] with value [" + partValue + "]"); } } } } } MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream()); hmethod.setRequestEntity(request); String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\""; Header header = new Header("Content-Type", contentTypeMtom); hmethod.addRequestHeader(header); }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server// www.j ava2 s. c om * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, @SuppressWarnings("unused") final String port, @SuppressWarnings("unused") final String security, final File fileAttachment) { String userName = uName; String password = pWord; Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); Properties props = System.getProperties(); props.put("mail.smtp.host", host); //$NON-NLS-1$ props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ boolean usingSSL = false; if (usingSSL) { props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } Session session = Session.getInstance(props, null); session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); 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); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } // set the Date: header msg.setSentDate(new Date()); // send the message int cnt = 0; do { cnt++; SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); fail = false; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } //wrong username or password, get new one if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { fail = true; userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) {//the user is done return false; } // else //try again userName = userAndPass.get(0); password = userAndPass.get(1); } } finally { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } while (fail && cnt < 6); } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); //mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return false; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); ex.printStackTrace(); } if (fail) { return false; } //else return true; }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {// w w w .j ava 2s . c om 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:org.jresponder.message.MessageRefImpl.java
/** * Render a message in the context of a particular subscriber * and subscription./*from w w w . j a v a2 s.co m*/ */ @Override public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber, Subscription aSubscription) { try { // prepare context Map<String, Object> myRenderContext = new HashMap<String, Object>(); myRenderContext.put("subscriber", aSubscriber); myRenderContext.put("subscription", aSubscription); myRenderContext.put("config", aSendConfig); myRenderContext.put("message", this); // render the whole file String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext); // now parse again with Jsoup Document myDocument = Jsoup.parse(myRenderedFileContents); String myHtmlBody = ""; String myTextBody = ""; // html body Elements myBodyElements = myDocument.select("#htmlbody"); if (!myBodyElements.isEmpty()) { myHtmlBody = myBodyElements.html(); } // text body Elements myJrTextBodyElements = myDocument.select("#textbody"); if (!myJrTextBodyElements.isEmpty()) { myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first()); } // now build the actual message MimeMessage myMimeMessage = aMimeMessage; // wrap it in a MimeMessageHelper - since some things are easier with that MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage); // set headers // subject myMimeMessageHelper.setSubject(TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext)); // TODO: implement DKIM, figure out subetha String mySenderEmailPattern = aSendConfig.getSenderEmailPattern(); String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext); myMimeMessage.setSender(new InternetAddress(mySenderEmail)); myMimeMessageHelper.setTo(aSubscriber.getEmail()); // from myMimeMessageHelper.setFrom( TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext), TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext)); // see how to set body // if we have both text and html, then do multipart if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) { // create wrapper multipart/alternative part MimeMultipart ma = new MimeMultipart("alternative"); myMimeMessage.setContent(ma); // create the plain text BodyPart plainText = new MimeBodyPart(); plainText.setText(myTextBody); ma.addBodyPart(plainText); // create the html part BodyPart html = new MimeBodyPart(); html.setContent(myHtmlBody, "text/html"); ma.addBodyPart(html); } // if only HTML, then just use that else if (myHtmlBody.trim().length() > 0) { myMimeMessageHelper.setText(myHtmlBody, true); } // if only text, then just use that else if (myTextBody.trim().length() > 0) { myMimeMessageHelper.setText(myTextBody, false); } // if neither text nor HTML, then the message is being skipped, // so we just return null else { return false; } return true; } catch (MessagingException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:org.fireflow.service.email.send.MailSenderImpl.java
/** * TODO ?/*w w w . j ava2 s. c o m*/ * @param mailSession * @param mailMessage * @return * @throws MessagingException * @throws AddressException * @throws ServiceInvocationException */ private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage) throws AddressException, MessagingException { MimeMessage mimeMsg = new MimeMessage(mailSession); //1?set from //Assert.notNull(mailMessage.getFrom(),"From address must not be null"); mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom())); //2?set mailto List<String> mailToList = mailMessage.getMailToList(); InternetAddress[] addressList = new InternetAddress[mailToList.size()]; for (int i = 0; i < mailToList.size(); i++) { String mailTo = mailToList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.TO, addressList); //3?set cc List<String> ccList = mailMessage.getCarbonCopyList(); if (ccList != null && ccList.size() > 0) { addressList = new InternetAddress[ccList.size()]; for (int i = 0; i < ccList.size(); i++) { String mailTo = ccList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.CC, addressList); } //4?set subject mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset()); //5?set sentDate if (this.sentDate != null) { mimeMsg.setSentDate(sentDate); } //6?set email body Multipart multiPart = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); if (mailMessage.getBodyIsHtml()) bp.setContent(mailMessage.getBody(), CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset()); else bp.setText(mailMessage.getBody(), mailServiceDef.getCharset()); multiPart.addBodyPart(bp); mimeMsg.setContent(multiPart); //7?set attachment //TODO ? return mimeMsg; }