List of usage examples for javax.mail.internet MimeMessage setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:at.molindo.notify.channel.mail.AbstractMailClient.java
@Override public synchronized void send(Dispatch dispatch) throws MailException { Message message = dispatch.getMessage(); String recipient = dispatch.getParams().get(MailChannel.RECIPIENT); String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME); String subject = message.getSubject(); try {/*from w w w. j ava 2 s . c o m*/ MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) { @Override protected void updateMessageID() throws MessagingException { String domain = _from.getAddress(); int idx = _from.getAddress().indexOf('@'); if (idx >= 0) { domain = domain.substring(idx + 1); } setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">"); } }; mm.setFrom(_from); mm.setSender(_from); InternetAddress replyTo = getReplyTo(); if (replyTo != null) { mm.setReplyTo(new Address[] { replyTo }); } mm.setHeader("X-Mailer", "molindo-notify"); mm.setSentDate(new Date()); mm.setRecipient(RecipientType.TO, new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName())); mm.setSubject(subject, CharsetUtils.UTF_8.displayName()); if (_format == Format.HTML) { if (message.getType() == Type.TEXT) { throw new MailException("can't send HTML mail from TEXT message", false); } mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) { mm.setText(message.getText(), CharsetUtils.UTF_8.displayName()); } else if (_format == Format.MULTI) { MimeBodyPart html = new MimeBodyPart(); html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); MimeBodyPart text = new MimeBodyPart(); text.setText(message.getText(), CharsetUtils.UTF_8.displayName()); /* * The formats are ordered by how faithful they are to the * original, with the least faithful first and the most faithful * last. (http://en.wikipedia.org/wiki/MIME#Alternative) */ MimeMultipart mmp = new MimeMultipart(); mmp.setSubType("alternative"); mmp.addBodyPart(text); mmp.addBodyPart(html); mm.setContent(mmp); } else { throw new NotifyRuntimeException( "unexpected format (" + _format + ") or type (" + message.getType() + ")"); } send(mm); } catch (final MessagingException e) { throw new MailException( "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e, isTemporary(e)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("utf8 unknown?", e); } }
From source file:com.stimulus.archiva.store.MessageStore.java
public void saveEmailChanges(MimeMessage message) throws MessagingException { logger.debug("saveEmailChanges"); String[] messageId = message.getHeader("Message-Id"); //try { System.out.println("Content:"+message.getContent()); } catch (Exception e) {} message.saveChanges();//from w w w. j a v a 2 s.co m if (messageId != null && messageId.length > 0) message.setHeader("Message-Id", messageId[0]); }
From source file:mitm.application.djigzo.james.mailets.NotifyTest.java
@Test public void testInvalidOriginator() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Notify mailet = new Notify(); mailetConfig.setInitParameter("template", "encryption-notification.ftl"); mailetConfig.setInitParameter("recipients", "originator"); mailetConfig.setInitParameter("processor", "testProcessor"); mailetConfig.setInitParameter("passThrough", "false"); mailet.init(mailetConfig);/* w ww . j av a2s . c om*/ MockMail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test\n", "text/plain"); message.setHeader("From", "!@#$%^&*("); message.saveChanges(); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("recipient@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals(0, listener.getSenders().size()); assertEquals(0, listener.getRecipients().size()); assertEquals(0, listener.getStates().size()); assertEquals(0, listener.getMessages().size()); assertEquals(0, listener.getMails().size()); assertNull(mail.getState()); }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail * //www.java2 s.c o m * @param mail The original Mail object * @param session Mail session * @return The MIME message */ private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException { // this will also check for email error InternetAddress from = new InternetAddress(mail.getFrom()); String recipients = mail.getHeader("To"); if (StringUtils.isBlank(recipients)) { recipients = mail.getTo(); } else { recipients = mail.getTo() + "," + recipients; } InternetAddress[] to = toInternetAddresses(recipients); recipients = mail.getHeader("Cc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getCc(); } else { recipients = mail.getCc() + "," + recipients; } InternetAddress[] cc = toInternetAddresses(recipients); recipients = mail.getHeader("Bcc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getBcc(); } else { recipients = mail.getBcc() + "," + recipients; } InternetAddress[] bcc = toInternetAddresses(recipients); if ((to == null) && (cc == null) && (bcc == null)) { LOGGER.info("No recipient -> skipping this email"); return null; } MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(from); if (to != null) { message.setRecipients(javax.mail.Message.RecipientType.TO, to); } if (cc != null) { message.setRecipients(javax.mail.Message.RecipientType.CC, cc); } if (bcc != null) { message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc); } message.setSubject(mail.getSubject(), EMAIL_ENCODING); for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) { message.setHeader(header.getKey(), header.getValue()); } if (mail.getHtmlPart() != null || mail.getAttachments() != null) { Multipart multipart = createMimeMultipart(mail, context); message.setContent(multipart); } else { message.setText(mail.getTextPart()); } message.setSentDate(new Date()); message.saveChanges(); return message; }
From source file:edu.stanford.muse.email.EmailFetcherStats.java
/** * fetch given message idx's in given folder -- @performance critical * * @param offset - the original offset of the first message in the messages array, important to initialize * for proper assignment of unique id or doc Id *//*from w w w .jav a 2s . c o m*/ //private void fetchUncachedMessages(String sanitizedFName, Folder folder, DocCache cache, List<Integer> msgIdxs) throws MessagingException, FileNotFoundException, IOException, GeneralSecurityException { private void fetchAndIndexMessages(Folder folder, Message[] messages, int offset, int totalMessages) throws MessagingException, IOException, GeneralSecurityException { //mark the processing of new batch if (offset == 0) fetchStartTime = System.currentTimeMillis(); currentStatus = JSONUtils.getStatusJSON( (emailStore instanceof MboxEmailStore) ? "Parsing " + folder.getName() + " (can take a while)..." : "Reading " + folder.getName() + "..."); // bulk fetch of all message headers int n = messages.length; // eliminate any messages the archive already has messages = removeMessagesAlreadyInArchive(archive, messages); log.info(n - messages.length + " message(s) already in the archive"); ArrayList<EmailDocument> emails = new ArrayList<EmailDocument>(); // for performance, we need to do bulk prefetches, instead of fetching 1 message at a time // prefetchedMessages will be a temp cache of prefetched messages int first_i_prefetched = -1, last_i_prefetched = -1; List<?> prefetchedMessages = null; // the type of this can be either list<string> if text only, otherwise list<mimemmessage> long highestUID = archive.getLastUIDForFolder(fetchedFolderInfo.accountKey, fetchedFolderInfo.longName); long lastAssignedUID = highestUID; boolean bodyTextOnly = !fetchConfig.downloadAttachments; try { archive.openForWrite(); for (int i = 0; i < messages.length; i++) { // critical step: (thanks, yourkit!) // null out the ref to the previous message, otherwise it stays in memory, and the heap effectively needs to be as big as the size of all messages if (i > 0) messages[i - 1] = null; if (isCancelled) break; Message m = messages[i]; MimeMessage mm = (MimeMessage) m; if (i >= last_i_prefetched) { // critical perf. step: do a bulk imap prefetch // the prefetch will fetch as many messages as possible up to a max buffer size, and return the messages prefetched // last_i_prefetched tracks what is the last index into idxs that we have prefetched. // when we run out of prefetched messages, we do another bulk prefetch prefetchedMessages = do_imap_prefetch(messages, i, folder, bodyTextOnly); if (prefetchedMessages != null) { first_i_prefetched = i; last_i_prefetched = i + prefetchedMessages.size(); } } int pctDone = ((i + offset) * 100) / totalMessages; long elapsedMillis = System.currentTimeMillis() - fetchStartTime; long unprocessedSecs = Util.getUnprocessedMessage(i + offset, totalMessages, elapsedMillis); int N_TEASERS = 50; // 50 ok here, because it takes a long time to fetch and process messages, so teaser computation is relatively not expensive int nTriesForThisMessage = 0; currentStatus = getStatusJSONWithTeasers( "Reading " + Util.commatize(totalMessages) + " messages from " + folder.getName() + "...", pctDone, elapsedMillis / 1000, unprocessedSecs, emails, N_TEASERS); int messageNum = mm.getMessageNumber(); try { long unique_id; // if we have uid, that's even better // don't use uid's for mbox, it has a bug and always gives -1 // see http://james.apache.org/server/rfclist/imap4/rfc2060.txt for uid spec if (folder instanceof UIDFolder && !(emailStore instanceof MboxEmailStore)) { long uid = ((UIDFolder) folder).getUID(m); unique_id = uid; } else unique_id = lastAssignedUID + 1 + i + offset; // +1 since i starts from 0 (but lastAssignedUID can be -1 -- is that safe? -sgh) if (unique_id > highestUID) highestUID = unique_id; String unique_id_as_string = Long.toString(unique_id); // well, we already converted to emaildoc above during removeMessagesAlreadyInArchive // not a serious perf. concern now, but revisit if needed EmailDocument ed = convertToEmailDocument(mm, unique_id_as_string); // this messageNum is mostly for debugging, it should not be used for equals etc. // need to check this again, because there might be duplicates such within the set we are currently processing. if (archive.containsDoc(ed)) { stats.nMessagesAlreadyPresent++; dataErrors.add("Duplicate message: " + ed); // note: report.jsp depends on this specific string continue; } MimeMessage originalMessage = mm; // this is the mm that has all the headers etc. List<Blob> attachmentsList = new ArrayList<Blob>(); // if we already have it prefetched, use the prefetched version List<String> contents = null; if (first_i_prefetched >= 0 && prefetchedMessages != null) { if (!fetchConfig.downloadAttachments) { // text only means the prefetchedMessages are stored directly as a list of strings String content = (String) prefetchedMessages.get(i - first_i_prefetched); // note: this_mm only has the prefetched content, but not the headers contents = new ArrayList<String>(); try { // a special for yahoo which routinely uses quoted-printable. content looks like =0A0D.... = etc. if (mm.isMimeType("multipart/alternative")) { Multipart mm_mp = (Multipart) mm.getContent(); Part p0 = mm_mp.getBodyPart(0); if (p0 instanceof com.sun.mail.imap.IMAPBodyPart) { String encoding = ((com.sun.mail.imap.IMAPBodyPart) p0).getEncoding(); if ("quoted-printable".equals(encoding)) { content = new String( Util.getBytesFromStream(javax.mail.internet.MimeUtility.decode( new java.io.ByteArrayInputStream(content.getBytes()), "quoted-printable"))); } } } } catch (Exception e) { Util.print_exception("Error trying to parse encoding of multipart", e, log); } contents.add(content); } else { // subtle issue here: the contentType of the prefetchedMessage needs to be be set to the original_mm's content-type. // this was found for cases where the original message is multipart-alternative with a text and html part. // if we don't set prefetchedMessage's content type, it gets a mime type of text/plain and a body = the entire multipart including both parts. // found on sgh's sent mail w/subject: "text to add in help" from Fri, 7 Jun 2013 MimeMessage prefetchedMessage = (MimeMessage) prefetchedMessages .get(i - first_i_prefetched); String contentTypeHeaders[] = originalMessage.getHeader("Content-Type"); String contentTypeHeader = null; if (contentTypeHeaders != null && contentTypeHeaders.length == 1) contentTypeHeader = contentTypeHeaders[0]; if (!Util.nullOrEmpty(contentTypeHeader)) // we do care about body structure, hang on to it prefetchedMessage.setHeader("Content-Type", contentTypeHeader); mm = prefetchedMessage; } prefetchedMessages.set(i - first_i_prefetched, null); // null out to save memory } if (contents == null) contents = processMessagePart(messageNum, originalMessage, mm, attachmentsList); // if mm is not prefetched, it is the same as original_mm // will also work, but will be slow as javamail accesses and fetches each mm separately, instead of using the bulk prefetched version // even when prefetched, the processMessagePart is somewhat expensive because the attachments have to be extracted etc. // we could overlap processMessagePart with do_imap_prefetch by prefetching in a separate thread, since prefetch is network limited. // but profiling shows processMessagePart takes only 1/4th the time of do_imap_prefetch so overlapping would be a relatively small gain. // not worth the effort right now. ed.attachments = attachmentsList; if (fetchConfig.downloadAttachments) ed.attachmentsYetToBeDownloaded = false; // we've already downloaded our attachments // concat all the contents parts StringBuilder sb = new StringBuilder(); for (String s : contents) { sb.append(s); sb.append("\n"); } String contentStr = sb.toString(); if (!messageLooksOk(contentStr)) { dataErrors.add("Skipping message as it seems to have very long words: " + ed); continue; } if (contentStr.length() > Config.MAX_TEXT_SIZE_TO_ANNOTATE) { dataErrors.add("Skipping message as it seems to be very long: " + contentStr.length() + " chars, while the max size message that will be annotated for display is " + Config.MAX_TEXT_SIZE_TO_ANNOTATE + " chars. Message = " + ed); // but we continue, don't skip the message entirely. See issue #111 } contentStr = IndexUtils.normalizeNewlines(contentStr); // just get rid of \r's archive.addDoc(ed, contentStr); List<LinkInfo> linkList = new ArrayList<LinkInfo>(); // linkList might be used only for slant IndexUtils.populateDocLinks(ed, contentStr, linkList, true); ed.links = linkList; stats.nMessagesAdded++; } catch (Exception ex) { // sometimes we get unexpected folder closed, so try again boolean retry = false; if (ex instanceof javax.mail.FolderClosedException) { log.warn("Oops, thread " + threadID + " got the folder closed in its face! " + ex.getMessage()); // sometimes we get this exception about folder closed // retry up to 3 times, then give up if (nTriesForThisMessage < 3) { retry = true; log.info("Re-opening email store; attempt #" + (nTriesForThisMessage + 1) + " for message " + i); nTriesForThisMessage++; messages = openFolderAndGetMessages(); fetchHeaders(messages); --i; // adjust the message index n try again } } if (!retry) { // we sometimes see UnsupportedEncodingException with x-utf8utf8 mime type and ParseException // nothing much can be done, just create a dummy doc and add it to the cache nErrors++; stats.nErrors++; EmailDocument ed = new EmailDocument(Integer.toString(messageNum)); log.warn("Exception reading message from " + folder_name() + " Message #" + messageNum + " " + ex.getMessage() + "\n" + Util.stackTrace(ex)); ed.setErrorString(Util.stackTrace(ex)); } } } } catch (Throwable t) { Util.print_exception(t, log); } finally { // if (cancelled && false) // TODO: disable for now as currently only indexes are rolled back and allDocs/blobs are not rolled back in sync yet // archive.rollbackIndexWrites(); // else currentStatus = JSONUtils.getStatusJSON("Saving archive..."); archive.close(); } fetchedFolderInfo.lastSeenUID = highestUID; log.info("at end of fetch, folder info is " + fetchedFolderInfo); log.info("emailfetcher thread completed, archive has " + archive.getAllDocs().size() + " docs"); }
From source file:net.malariagen.alfresco.action.CustomMailAction.java
public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef, final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) { // Create the mime mail message. // Hack: using an array here to get around the fact that inner classes // aren't closures. // The MimeMessagePreparator.prepare() signature does not allow us to // return a value and yet // we can't set a result on a bare, non-final object reference due to // Java language restrictions. final MimeMessageHelper[] messageRef = new MimeMessageHelper[1]; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { @SuppressWarnings("unchecked") public void prepare(MimeMessage mimeMessage) throws MessagingException { if (logger.isDebugEnabled()) { logger.debug(ruleAction.getParameterValues()); }/*from w w w. jav a 2 s .c om*/ messageRef[0] = new MimeMessageHelper(mimeMessage); // set header encoding if one has been supplied if (headerEncoding != null && headerEncoding.length() != 0) { mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding); } String listHeaders = (String) ruleAction.getParameterValue(PARAM_LIST_ID); if (listHeaders != null) { mimeMessage.setHeader("List-Id", "<" + listHeaders + "." + sysAdminParams.getAlfrescoHost() + ">"); mimeMessage.setHeader("X-Auto-Response-Suppress", "All"); mimeMessage.setHeader("Precedence", "list"); mimeMessage.setHeader("auto-submitted", "auto-generated"); } // set recipient // I don't think this is used - see getRecipients in parent String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { messageRef[0].setTo(to); // Note: there is no validation on the username to check // that it actually is an email address. // TODO Fix this. Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC); if (ccValue != null) { if (ccValue instanceof String) { String cc = (String) ccValue; if (cc.length() > 0) { messageRef[0].setCc(cc); } } else if (ccValue instanceof List<?>) { List<String> s = (List<String>) ccValue; messageRef[0].setCc((String[]) s.toArray()); } else if (ccValue.getClass().isArray()) { messageRef[0].setCc((String[]) ccValue); } } Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC); if (bccValue != null) { if (bccValue instanceof String) { String bcc = (String) bccValue; if (bcc.length() > 0) { messageRef[0].setBcc(bcc); } } else if (bccValue instanceof List<?>) { List<String> s = (List<String>) bccValue; messageRef[0].setBcc((String[]) s.toArray()); } else if (bccValue.getClass().isArray()) { messageRef[0].setCc((String[]) bccValue); } } } else { // see if multiple recipients have been supplied - as a list // of authorities Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> authorities = null; if (authoritiesValue != null) { if (authoritiesValue instanceof String) { authorities = new ArrayList<String>(1); authorities.add((String) authoritiesValue); } else { authorities = (List<String>) authoritiesValue; } } if (authorities != null && authorities.size() != 0) { List<String> recipients = new ArrayList<String>(authorities.size()); if (logger.isTraceEnabled()) { logger.trace(authorities.size() + " recipient(s) for mail"); } for (String authority : authorities) { final AuthorityType authType = AuthorityType.getAuthorityType(authority); if (logger.isTraceEnabled()) { logger.trace(" authority type: " + authType); } if (authType.equals(AuthorityType.USER)) { if (personService.personExists(authority) == true) { NodeRef person = personService.getPerson(authority); if (!personService.isEnabled(authority) && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) { continue; } String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0 && validateAddress(address)) { if (logger.isTraceEnabled()) { logger.trace("Recipient (person) exists in Alfresco with known email."); } recipients.add(address); } else { if (logger.isTraceEnabled()) { logger.trace( "Recipient (person) exists in Alfresco without known email."); } // If the username looks like an email // address, we'll use that. if (validateAddress(authority)) { recipients.add(authority); } } } else { if (logger.isTraceEnabled()) { logger.trace("Recipient does not exist in Alfresco."); } if (validateAddress(authority)) { recipients.add(authority); } } } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) { if (logger.isTraceEnabled()) { logger.trace("Recipient is a group..."); } // Notify all members of the group Set<String> users; if (authType.equals(AuthorityType.GROUP)) { users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false); } else { users = authorityService.getAllAuthorities(AuthorityType.USER); } for (String userAuth : users) { if (personService.personExists(userAuth) == true) { NodeRef person = personService.getPerson(userAuth); String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0) { recipients.add(address); if (logger.isTraceEnabled()) { logger.trace(" Group member email is known."); } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member email not known."); } if (validateAddress(authority)) { recipients.add(userAuth); } } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member person not found"); } if (validateAddress(authority)) { recipients.add(userAuth); } } } } } if (logger.isTraceEnabled()) { logger.trace(recipients.size() + " valid recipient(s)."); } if (recipients.size() > 0) { messageRef[0].setTo(recipients.toArray(new String[recipients.size()])); } else { // All recipients were invalid throw new MailPreparationException("All recipients for the mail action were invalid"); } } else { // No recipients have been specified throw new MailPreparationException("No recipient has been specified for the mail action"); } } // from person - not to be performed for the "admin" or "system" // users NodeRef fromPerson = null; final String currentUserName = authService.getCurrentUserName(); final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] { AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() }); if (!usersNotToBeUsedInFromField.contains(currentUserName)) { fromPerson = personService.getPerson(currentUserName); } if (isFromEnabled()) { // Use the FROM parameter in preference to calculating // values. String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from != null && from.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("from specified as a parameter, from:" + from); } // Check whether or not to use a personal name for the // email (will be RFC 2047 encoded) String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME); if (fromPersonalName != null && fromPersonalName.length() > 0) { try { messageRef[0].setFrom(from, fromPersonalName); } catch (UnsupportedEncodingException error) { // Uses the JVM's default encoding, can never be // unsupported. Just in case, revert to simple // email messageRef[0].setFrom(from); } } else { messageRef[0].setFrom(from); } setReplyTo(ruleAction, messageRef, from); } else { // set the from address from the current user String fromActualUser = null; if (fromPerson != null) { fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("looked up email address for :" + fromPerson + " email from " + fromActualUser); } messageRef[0].setFrom(fromActualUser); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } else { // from system or user does not have email address messageRef[0].setFrom(fromDefaultAddress); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } } } else { if (logger.isDebugEnabled()) { logger.debug("from not enabled - sending from default address:" + fromDefaultAddress); } // from is not enabled. messageRef[0].setFrom(fromDefaultAddress); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } // set subject line messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll // send the email to that address instead. // We'll prefix the subject with the original recipient, but // leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO); if (emailRecipient == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { emailRecipient = obj.toString(); } } String recipientPrefixedSubject = "(" + emailRecipient + ") " + (String) ruleAction.getParameterValue(PARAM_SUBJECT); messageRef[0].setSubject(recipientPrefixedSubject); } // See if an email template has been specified String text = null; // templateRef: either a nodeRef or classpath (see // ClasspathRepoTemplateLoader) Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE); String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref); if (templateRef != null) { Map<String, Object> suppliedModel = null; if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) { Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL); if (m instanceof Map) { suppliedModel = (Map<String, Object>) m; } else { logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString()); } } // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson); // Determine the locale to use to send the email. Locale locale = recipient.getSecond(); if (locale == null) { locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE); } if (locale == null) { locale = sender.getSecond(); } // set subject line String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT); Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS); Object[] subjectParams = null; // Javasctipt pass SubjectParams as ArrayList. see MNT-12534 if (subjectParamsObject instanceof List) { subjectParams = ((List<Object>) subjectParamsObject).toArray(); } else if (subjectParamsObject instanceof Object[]) { subjectParams = (Object[]) subjectParamsObject; } else { if (subjectParamsObject != null) { subjectParams = new Object[] { subjectParamsObject.toString() }; } } String localizedSubject = getLocalizedSubject(subject, subjectParams, locale); if (locale == null) { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model); } else { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model, locale); } if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll // send the email to that address instead. // We'll prefix the subject with the original recipient, // but leave the email message unchanged in every other // way. messageRef[0].setTo(testModeRecipient); String emailRecipient = recipient.getFirst(); String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject; messageRef[0].setSubject(recipientPrefixedSubject); } else { messageRef[0].setTo(recipient.getFirst()); messageRef[0].setSubject(localizedSubject); } } // set the text body of the message boolean isHTML = false; if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } if (text != null) { if (isHTML(text)) { isHTML = true; } } else { text = (String) ruleAction.getParameterValue(PARAM_HTML); if (text != null) { // assume HTML isHTML = true; } } if (text != null) { messageRef[0].setText(text, isHTML); } } private void setReplyTo(final Action ruleAction, final MimeMessageHelper[] messageRef, String from) throws MessagingException { // ResponseNode can be a Long as well as Text Object responseNode = ruleAction.getParameterValue(PARAM_RESPONSE_NODE); if (responseNode != null) { // Assuming address is valid... String[] parts = from.split("@"); messageRef[0].setReplyTo(parts[0] + "+" + responseNode + "@" + parts[1]); } } }; MimeMessage mimeMessage = mailService.createMimeMessage(); try { mailPreparer.prepare(mimeMessage); } catch (Exception e) { // We're forced to catch java.lang.Exception here. Urgh. if (logger.isWarnEnabled()) { logger.warn("Unable to prepare mail message. Skipping.", e); } return null; } return messageRef[0]; }
From source file:com.flexive.shared.FxMailUtils.java
/** * Sends an email/* ww w. j a v a2s . co m*/ * * @param SMTPServer IP Address of the SMTP server * @param subject subject of the email * @param textBody plain text * @param htmlBody html text * @param to recipient * @param cc cc recepient * @param bcc bcc recipient * @param from sender * @param replyTo reply-to address * @param mimeAttachments strings containing mime encoded attachments * @throws FxApplicationException on errors */ public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to, String cc, String bcc, String from, String replyTo, String... mimeAttachments) throws FxApplicationException { try { // Set the mail server java.util.Properties properties = System.getProperties(); if (SMTPServer != null) properties.put("mail.smtp.host", SMTPServer); // Get a session and create a new message javax.mail.Session session = javax.mail.Session.getInstance(properties, null); MimeMessage msg = new MimeMessage(session); // Set the sender if (StringUtils.isBlank(from)) msg.setFrom(); // Uses local IP Adress and the user under which the server is running else { msg.setFrom(createAddress(from)); } if (!StringUtils.isBlank(replyTo)) msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false))); // Set the To, Cc and Bcc fields if (!StringUtils.isBlank(to)) msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false))); if (!StringUtils.isBlank(cc)) msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false))); if (!StringUtils.isBlank(bcc)) msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false))); // Set the subject msg.setSubject(subject, "UTF-8"); String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\""; StringBuilder body = new StringBuilder(5000); if (mimeAttachments.length > 0) { sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\""; body.append("This is a multi-part message in MIME format.\n\n"); body.append("--" + BOUNDARY2 + "\n"); body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n"); } if (textBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/plain; charset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); body.append(encodeQuotedPrintable(textBody)).append("\n"); } if (htmlBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); if (htmlBody.toLowerCase().indexOf("<html>") < 0) { body.append("<HTML><HEAD>\n<TITLE></TITLE>\n"); body.append( "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n"); body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n"); } else body.append(encodeQuotedPrintable(htmlBody)).append("\n"); } body.append("\n--" + BOUNDARY1 + "--\n"); if (mimeAttachments.length > 0) { for (String mimeAttachment : mimeAttachments) { body.append("\n--" + BOUNDARY2 + "\n"); body.append(mimeAttachment).append("\n"); } body.append("\n--" + BOUNDARY2 + "--\n"); } msg.setDataHandler( new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType))); // Set the header msg.setHeader("X-Mailer", "JavaMailer"); // Set the sent date msg.setSentDate(new java.util.Date()); // Send the message javax.mail.Transport.send(msg); } catch (AddressException e) { throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef()); } catch (javax.mail.MessagingException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (IOException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (EncoderException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } }
From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java
/** * Creates empty mail.//from www. ja va 2 s. c o m * * @param build build. * @param listener listener. * @return empty mail. * @throws MessagingException exception if any. */ protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException { MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession()); // TODO: I'd like to put the URL to the page in here, // but how do I obtain that? msg.setContent("", "text/plain"); msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress())); msg.setSentDate(new Date()); Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>(); StringTokenizer tokens = new StringTokenizer(getRecipients()); while (tokens.hasMoreTokens()) { String address = tokens.nextToken(); if (address.startsWith("upstream-individuals:")) { // people who made a change in the upstream String projectName = address.substring("upstream-individuals:".length()); AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class); if (up == null) { listener.getLogger().println("No such project exist: " + projectName); continue; } includeCulpritsOf(up, build, listener, rcp); } else { // ordinary address try { rcp.add(new InternetAddress(address)); } catch (AddressException e) { // report bad address, but try to send to other addresses e.printStackTrace(listener.error(e.getMessage())); } } } if (CollectionUtils.isNotEmpty(upstreamProjects)) { for (AbstractProject project : upstreamProjects) { includeCulpritsOf(project, build, listener, rcp); } } if (sendToIndividuals) { Set<User> culprits = build.getCulprits(); if (debug) listener.getLogger() .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)==" + culprits.size()); rcp.addAll(buildCulpritList(listener, culprits)); } msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()])); AbstractBuild<?, ?> pb = build.getPreviousBuild(); if (pb != null) { MailMessageIdAction b = pb.getAction(MailMessageIdAction.class); if (b != null) { msg.setHeader("In-Reply-To", b.messageId); msg.setHeader("References", b.messageId); } } return msg; }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail.//from w ww. ja v a 2s. com * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail.//from w w w.j av a 2 s.c om * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }