List of usage examples for javax.mail.internet MimeMessage getHeader
@Override public String getHeader(String name, String delimiter) throws MessagingException
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testClearSignDefaultProtectedHeader() throws Exception { MimeMessage message = loadMessage("normal-message-with-attach.eml"); SMIMEBuilder builder = new SMIMEBuilderImpl(message); builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(), SMIMESigningAlgorithm.SHA1WITHRSA); builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain())); builder.sign(SMIMESignMode.CLEAR);/* ww w .ja va2 s . co m*/ MimeMessage newMessage = builder.buildMessage(); File file = new File(tempDir, "testClearSignDefaultProtectedHeader.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage)); checkForSourceHeaders(newMessage); File opensslOutputFile = new File(tempDir, "testClearSignDefaultProtectedHeader-openssl.eml"); verifyMessage(file, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("multipart/mixed")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); assertEquals("normal message with attachment", newMessage.getHeader("subject", ",")); assertEquals("<test@example.com>", message.getHeader("to", ",")); assertNull(newMessage.getHeader("from")); }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testClearSignExtraCRLFPreamble() throws Exception { MimeMessage message = loadMessage("extra-cr-lf-preamble.eml"); SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from"); builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(), SMIMESigningAlgorithm.SHA1WITHRSA); builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain())); builder.sign(SMIMESignMode.CLEAR);//from w ww.j av a2 s . com MimeMessage newMessage = builder.buildMessage(); File file = new File(tempDir, "extra-cr-lf-preamble-signed.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE, SMIMEUtils.dissectSigned((Multipart) newMessage.getContent())[1].getContentType()); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage)); File opensslOutputFile = new File(tempDir, "extra-cr-lf-preamble-openssl.eml"); verifyMessage(file, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("multipart/mixed")); assertEquals("Martijn Brinkers <martijn@djigzo.com>", newMessage.getHeader("from", ",")); assertEquals("Martijn Brinkers <martijn@djigzo.com>", newMessage.getHeader("to", ",")); assertEquals("test multiple attachments extra CR/LF preamble", newMessage.getHeader("subject", ",")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testClearSignNoFromProtectedHeader() throws Exception { MimeMessage message = loadMessage("normal-message-with-attach.eml"); SMIMEBuilder builder = new SMIMEBuilderImpl(message, "subject", "to"); builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(), SMIMESigningAlgorithm.SHA1WITHRSA); builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain())); builder.sign(SMIMESignMode.CLEAR);/*from w w w. j a v a 2s .c o m*/ MimeMessage newMessage = builder.buildMessage(); File file = new File(tempDir, "testClearSignNoFromProtectedHeader.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage)); checkForSourceHeaders(newMessage); File opensslOutputFile = new File(tempDir, "testClearSignNoFromProtectedHeader-openssl.eml"); verifyMessage(file, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("multipart/mixed")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); // the message should contain the subject assertEquals("normal message with attachment", newMessage.getHeader("subject", ",")); assertEquals("<test@example.com>", message.getHeader("to", ",")); assertNull(newMessage.getHeader("from")); }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testClearSignDeprecatedHeaders() throws Exception { MimeMessage message = loadMessage("simple-text-message.eml"); SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from"); builder.setUseDeprecatedContentTypes(true); builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(), SMIMESigningAlgorithm.SHA1WITHRSA); builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain())); builder.sign(SMIMESignMode.CLEAR);/*from ww w . j a v a 2 s . c om*/ MimeMessage newMessage = builder.buildMessage(); File file = new File(tempDir, "testClearSignDeprecatedHeaders.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); SMIMEUtils.dissectSigned((Multipart) newMessage.getContent()); assertEquals(SMIMEHeader.DEPRECATED_DETACHED_SIGNATURE_TYPE, SMIMEUtils.dissectSigned((Multipart) newMessage.getContent())[1].getContentType()); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage)); File opensslOutputFile = new File(tempDir, "testClearSignDeprecatedHeaders-openssl.eml"); verifyMessage(file, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("text/plain")); assertEquals("test@example.com", newMessage.getHeader("from", ",")); assertEquals("test@example.com", newMessage.getHeader("to", ",")); assertEquals("test simple message", newMessage.getHeader("subject", ",")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); String content = (String) newMessage.getContent(); assertEquals("test", content.trim()); }
From source file:davmail.exchange.ExchangeSession.java
protected List<InternetAddress> getAllRecipients(MimeMessage mimeMessage) throws MessagingException { List<InternetAddress> recipientList = new ArrayList<InternetAddress>(); for (String recipientHeader : RECIPIENT_HEADERS) { final String recipientHeaderValue = mimeMessage.getHeader(recipientHeader, ","); if (recipientHeaderValue != null) { // parse headers in non strict mode recipientList.addAll(Arrays.asList(InternetAddress.parseHeader(recipientHeaderValue, false))); }// w w w. jav a 2 s .c o m } return recipientList; }
From source file:davmail.exchange.dav.DavExchangeSession.java
/** * Create message in specified folder.//from www. ja va 2 s . c om * Will overwrite an existing message with same messageName in the same folder * * @param folderPath Exchange folder path * @param messageName message name * @param properties message properties (flags) * @param mimeMessage MIME message * @throws IOException when unable to create message */ @Override public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException { String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName); PropPatchMethod patchMethod; List<PropEntry> davProperties = buildProperties(properties); if (properties != null && properties.containsKey("draft")) { // note: draft is readonly after create, create the message first with requested messageFlags davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft"))); } if (properties != null && properties.containsKey("mailOverrideFormat")) { davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat"))); } if (properties != null && properties.containsKey("messageFormat")) { davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat"))); } if (!davProperties.isEmpty()) { patchMethod = new PropPatchMethod(messageUrl, davProperties); try { // update message with blind carbon copy and other flags int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine()); } } finally { patchMethod.releaseConnection(); } } // update message body PutMethod putmethod = new PutMethod(messageUrl); putmethod.setRequestHeader("Translate", "f"); putmethod.setRequestHeader("Content-Type", "message/rfc822"); try { // use same encoding as client socket reader ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); baos.close(); putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int code = httpClient.executeMethod(putmethod); // workaround for misconfigured Exchange server if (code == HttpStatus.SC_NOT_ACCEPTABLE) { LOGGER.warn( "Draft message creation failed, failover to property update. Note: attachments are lost"); ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>(); propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ","))); propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ","))); propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ","))); MimePart mimePart = mimeMessage; if (mimeMessage.getContent() instanceof MimeMultipart) { MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent(); for (int i = 0; i < multiPart.getCount(); i++) { String contentType = multiPart.getBodyPart(i).getContentType(); if (contentType.startsWith("text/")) { mimePart = (MimePart) multiPart.getBodyPart(i); break; } } } String contentType = mimePart.getContentType(); if (contentType.startsWith("text/plain")) { propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent())); } else if (contentType.startsWith("text/html")) { propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent())); } else { LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty"); } propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ","))); PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList); try { int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod); if (patchStatus == HttpStatus.SC_MULTI_STATUS) { code = HttpStatus.SC_OK; } } finally { propPatchMethod.releaseConnection(); } } if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) { // first delete draft message if (!davProperties.isEmpty()) { try { DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl); } catch (IOException e) { LOGGER.warn("Unable to delete draft message"); } } if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) { throw new InsufficientStorageException(putmethod.getStatusText()); } else { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine()); } } } catch (MessagingException e) { throw new IOException(e.getMessage()); } finally { putmethod.releaseConnection(); } try { // need to update bcc after put if (mimeMessage.getHeader("Bcc") != null) { davProperties = new ArrayList<PropEntry>(); davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ","))); patchMethod = new PropPatchMethod(messageUrl, davProperties); try { // update message with blind carbon copy int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine()); } } finally { patchMethod.releaseConnection(); } } } catch (MessagingException e) { throw new IOException(e.getMessage()); } }
From source file:com.zimbra.cs.service.mail.ToXML.java
/** Encodes a Message object into <m> element with <mp> elements for * message body.//from w ww. j a va 2 s. c om * @param parent The Element to add the new <tt><m></tt> to. * @param ifmt The formatter to sue when serializing item ids. * @param msg The Message to serialize. * @param part If non-null, serialize this message/rfc822 subpart of * the Message instead of the Message itself. * @param maxSize TODO * @param wantHTML <tt>true</tt> to prefer HTML parts as the "body", * <tt>false</tt> to prefer text/plain parts. * @param neuter Whether to rename "src" attributes on HTML <img> tags. * @param headers Extra message headers to include in the returned element. * @param serializeType If <tt>false</tt>, always serializes as an * <tt><m></tt> element. * @param bestEffort If <tt>true</tt>, errors serializing part content * are swallowed. * @return The newly-created <tt><m></tt> Element, which has already * been added as a child to the passed-in <tt>parent</tt>. * @throws ServiceException */ private static Element encodeMessageAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt, Message msg, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers, boolean serializeType, boolean wantExpandGroupInfo, boolean bestEffort, boolean encodeMissingBlobs, MsgContent wantContent) throws ServiceException { Element m = null; boolean success = false; try { boolean wholeMessage = part == null || part.trim().isEmpty(); if (wholeMessage) { m = encodeMessageCommon(parent, ifmt, octxt, msg, NOTIFY_FIELDS, serializeType); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg)); } else { m = parent.addElement(MailConstants.E_MSG); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg)); m.addAttribute(MailConstants.A_PART, part); } MimeMessage mm = null; try { String requestedAccountId = octxt.getmRequestedAccountId(); String authtokenAccountId = octxt.getmAuthTokenAccountId(); boolean isDecryptionNotAllowed = StringUtils.isNotEmpty(authtokenAccountId) && !authtokenAccountId.equalsIgnoreCase(requestedAccountId); if (isDecryptionNotAllowed && Mime.isEncrypted(msg.getMimeMessage(false).getContentType())) { mm = msg.getMimeMessage(false); } else { mm = msg.getMimeMessage(); } } catch (MailServiceException e) { if (encodeMissingBlobs && MailServiceException.NO_SUCH_BLOB.equals(e.getCode())) { ZimbraLog.mailbox.error("Unable to get blob while encoding message", e); encodeEmail(m, msg.getSender(), EmailType.FROM); encodeEmail(m, msg.getSender(), EmailType.SENDER); if (msg.getRecipients() != null) { addEmails(m, Mime.parseAddressHeader(msg.getRecipients()), EmailType.TO); } m.addAttribute(MailConstants.A_SUBJECT, msg.getSubject()); Element mimePart = m.addElement(MailConstants.E_MIMEPART); mimePart.addAttribute(MailConstants.A_PART, 1); mimePart.addAttribute(MailConstants.A_BODY, true); mimePart.addAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_TEXT_PLAIN); String errMsg = L10nUtil.getMessage(L10nUtil.MsgKey.errMissingBlob, msg.getAccount().getLocale(), ifmt.formatItemId(msg)); m.addAttribute(MailConstants.E_FRAG, errMsg, Element.Disposition.CONTENT); mimePart.addAttribute(MailConstants.E_CONTENT, errMsg, Element.Disposition.CONTENT); success = true; //not really success, but mark as such so the element is appended correctly return m; } throw e; } if (!wholeMessage) { MimePart mp = Mime.getMimePart(mm, part); if (mp == null) { throw MailServiceException.NO_SUCH_PART(part); } Object content = Mime.getMessageContent(mp); if (!(content instanceof MimeMessage)) { throw MailServiceException.NO_SUCH_PART(part); } mm = (MimeMessage) content; } else { part = ""; } // Add fragment before emails to maintain consistent ordering // of elements with encodeConversation - need to do this to // overcome JAXB issues. String fragment = msg.getFragment(); if (fragment != null && !fragment.isEmpty()) { m.addAttribute(MailConstants.E_FRAG, fragment, Element.Disposition.CONTENT); } addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM); addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER); addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO); addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO); addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC); addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC); addEmails(m, Mime.parseAddressHeader(mm.getHeader("Resent-From", null), false), EmailType.RESENT_FROM); // read-receipts only get sent by the mailbox's owner if (!(octxt.isDelegatedRequest(msg.getMailbox()) && octxt.isOnBehalfOfRequest(msg.getMailbox()))) { addEmails(m, Mime.parseAddressHeader(mm, "Disposition-Notification-To"), EmailType.READ_RECEIPT); } String calIntendedFor = msg.getCalendarIntendedFor(); m.addAttribute(MailConstants.A_CAL_INTENDED_FOR, calIntendedFor); String subject = Mime.getSubject(mm); if (subject != null) { m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject), Element.Disposition.CONTENT); } String messageID = mm.getMessageID(); if (messageID != null && !messageID.trim().isEmpty()) { m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID), Element.Disposition.CONTENT); } if (wholeMessage && msg.isDraft()) { if (!msg.getDraftOrigId().isEmpty()) { ItemId origId = new ItemId(msg.getDraftOrigId(), msg.getMailbox().getAccountId()); m.addAttribute(MailConstants.A_ORIG_ID, ifmt.formatItemId(origId)); } if (!msg.getDraftReplyType().isEmpty()) { m.addAttribute(MailConstants.A_REPLY_TYPE, msg.getDraftReplyType()); } if (!msg.getDraftIdentityId().isEmpty()) { m.addAttribute(MailConstants.A_IDENTITY_ID, msg.getDraftIdentityId()); } if (!msg.getDraftAccountId().isEmpty()) { m.addAttribute(MailConstants.A_FOR_ACCOUNT, msg.getDraftAccountId()); } String inReplyTo = mm.getHeader("In-Reply-To", null); if (inReplyTo != null && !inReplyTo.isEmpty()) { m.addAttribute(MailConstants.E_IN_REPLY_TO, StringUtil.stripControlCharacters(inReplyTo), Element.Disposition.CONTENT); } if (msg.getDraftAutoSendTime() != 0) { m.addAttribute(MailConstants.A_AUTO_SEND_TIME, msg.getDraftAutoSendTime()); } } if (!wholeMessage) { m.addAttribute(MailConstants.A_SIZE, mm.getSize()); } Date sent = mm.getSentDate(); if (sent != null) { m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime()); } Calendar resent = DateUtil.parseRFC2822DateAsCalendar(mm.getHeader("Resent-Date", null)); if (resent != null) { m.addAttribute(MailConstants.A_RESENT_DATE, resent.getTimeInMillis()); } if (msg.isInvite() && msg.hasCalendarItemInfos()) { encodeInvitesForMessage(m, ifmt, octxt, msg, NOTIFY_FIELDS, neuter); } if (headers != null) { for (String name : headers) { String[] values = mm.getHeader(name); if (values != null) { for (int i = 0; i < values.length; i++) { m.addKeyValuePair(name, values[i], MailConstants.A_HEADER, MailConstants.A_ATTRIBUTE_NAME); } } } } List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(msg)); if (parts != null && !parts.isEmpty()) { Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML); addParts(m, parts.get(0), bodies, part, maxSize, neuter, false, getDefaultCharset(msg), bestEffort, wantContent); } if (wantExpandGroupInfo) { ZimbraLog.gal.trace("want expand group info"); Account authedAcct = octxt.getAuthenticatedUser(); Account requestedAcct = msg.getMailbox().getAccount(); encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct); } else { ZimbraLog.gal.trace("do not want expand group info"); } success = true; // update crypto flags - isSigned/isEncrypted if (SmimeHandler.getHandler() != null) { if (!wholeMessage) { // check content type of attachment message for encryption flag SmimeHandler.getHandler().updateCryptoFlags(msg, m, mm, mm); } else { MimeMessage originalMimeMessage = msg.getMimeMessage(false); SmimeHandler.getHandler().updateCryptoFlags(msg, m, originalMimeMessage, mm); } } // if the mime it is signed if (Mime.isMultipartSigned(mm.getContentType()) || Mime.isPKCS7Signed(mm.getContentType())) { ZimbraLog.mailbox .debug("The message is signed. Forwarding it to SmimeHandler for signature verification."); if (SmimeHandler.getHandler() != null) { SmimeHandler.getHandler().verifyMessageSignature(msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol()); } } else { // if the original mime message was PKCS7-signed and it was // decoded and stored in cache as plain mime if ((mm instanceof Mime.FixedMimeMessage) && ((Mime.FixedMimeMessage) mm).isPKCS7Signed()) { if (SmimeHandler.getHandler() != null) { SmimeHandler.getHandler().addPKCS7SignedMessageSignatureDetails( msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol()); } } } return m; } catch (IOException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (MessagingException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } finally { // don't leave turds around if we're going to retry if (!success && !bestEffort && m != null) { m.detach(); } } }
From source file:com.sonicle.webtop.mail.Service.java
public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent) throws MessagingException { MimeMessage reply = new MimeMessage(account.getMailSession()); /*//from w ww . j ava2s .co m * Have to manipulate the raw Subject header so that we don't lose * any encoding information. This is safe because "Re:" isn't * internationalized and (generally) isn't encoded. If the entire * Subject header is encoded, prefixing it with "Re: " still leaves * a valid and correct encoded header. */ String subject = orig.getHeader("Subject", null); if (subject != null) { if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) { subject = "Re: " + subject; } reply.setHeader("Subject", subject); } Address a[] = null; if (!fromSent) a = orig.getReplyTo(); else { Address ax[] = orig.getRecipients(RecipientType.TO); if (ax != null) { a = new Address[1]; a[0] = ax[0]; } } reply.setRecipients(Message.RecipientType.TO, a); if (replyToAll) { Vector v = new Vector(); Session session = account.getMailSession(); // add my own address to list InternetAddress me = InternetAddress.getLocalAddress(session); if (me != null) { v.addElement(me); } // add any alternate names I'm known by String alternates = null; if (session != null) { alternates = session.getProperty("mail.alternates"); } if (alternates != null) { eliminateDuplicates(v, InternetAddress.parse(alternates, false)); } // should we Cc all other original recipients? String replyallccStr = null; boolean replyallcc = false; if (session != null) { replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false); } // add the recipients from the To field so far eliminateDuplicates(v, a); a = orig.getRecipients(Message.RecipientType.TO); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { if (replyallcc) { reply.addRecipients(Message.RecipientType.CC, a); } else { reply.addRecipients(Message.RecipientType.TO, a); } } a = orig.getRecipients(Message.RecipientType.CC); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { reply.addRecipients(Message.RecipientType.CC, a); } // don't eliminate duplicate newsgroups a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS); if (a != null && a.length > 0) { reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a); } } String msgId = orig.getHeader("Message-Id", null); if (msgId != null) { reply.setHeader("In-Reply-To", msgId); } /* * Set the References header as described in RFC 2822: * * The "References:" field will contain the contents of the parent's * "References:" field (if any) followed by the contents of the parent's * "Message-ID:" field (if any). If the parent message does not contain * a "References:" field but does have an "In-Reply-To:" field * containing a single message identifier, then the "References:" field * will contain the contents of the parent's "In-Reply-To:" field * followed by the contents of the parent's "Message-ID:" field (if * any). If the parent has none of the "References:", "In-Reply-To:", * or "Message-ID:" fields, then the new message will have no * "References:" field. */ String refs = orig.getHeader("References", " "); if (refs == null) { // XXX - should only use if it contains a single message identifier refs = orig.getHeader("In-Reply-To", " "); } if (msgId != null) { if (refs != null) { refs = MimeUtility.unfold(refs) + " " + msgId; } else { refs = msgId; } } if (refs != null) { reply.setHeader("References", MimeUtility.fold(12, refs)); } //try { // setFlags(answeredFlag, true); //} catch (MessagingException mex) { // // ignore it //} return reply; }
From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java
@Test public void sendEmailWithExtraHeaders() throws Exception { final List<List<String>> headers = new ArrayList<List<String>>(); List<String> row1 = new ArrayList<String>(); row1.add("X-Mailer"); row1.add("Bonita Mailer"); headers.add(row1);/*from w w w. java 2 s . c o m*/ List<String> row2 = new ArrayList<String>(); row2.add("Message-ID"); row2.add("IWantToHackTheServer"); headers.add(row2); List<String> row3 = new ArrayList<String>(); row3.add("X-Priority"); row3.add("2 (High)"); headers.add(row3); List<String> row4 = new ArrayList<String>(); row4.add("Content-Type"); row4.add("video/mpeg"); headers.add(row4); List<String> row5 = new ArrayList<String>(); row5.add("WhatIWant"); row5.add("anyValue"); headers.add(row5); List<String> row6 = new ArrayList<String>(); row6.add("From"); row6.add("alice@bob.charly"); headers.add(row6); List<String> row7 = new ArrayList<String>(); row7.add(null); row7.add(null); headers.add(row7); final Map<String, Object> parameters = getBasicSettings(); parameters.put("headers", headers); executeConnector(parameters); final List<WiserMessage> messages = server.getMessages(); assertEquals(1, messages.size()); final WiserMessage message = messages.get(0); assertEquals("alice@bob.charly", message.getEnvelopeSender()); assertEquals(ADDRESSJOHN, message.getEnvelopeReceiver()); final MimeMessage mime = message.getMimeMessage(); assertEquals(SUBJECT, mime.getSubject()); assertEquals(0, mime.getSize()); assertEquals("Bonita Mailer", mime.getHeader("X-Mailer", "")); assertEquals("2 (High)", mime.getHeader("X-Priority", "")); assertEquals("anyValue", mime.getHeader("WhatIWant", "")); assertNotSame("alice@bob.charly", mime.getHeader("From")); assertFalse(mime.getContentType().contains("video/mpeg")); assertNotSame("IWantToHackTheServer", mime.getHeader("Message-ID")); }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
public void testCommonsEmailOneWaySeparateSessions() { Queue emailQueue = null;// w w w .j a va 2 s. co m MessageConsumer consumer = null; MessageProducer producer = null; Session clientSession = null; Session listenerSession = null; // it is not necessary to use the Email interface here // Email is used here just to allow for multiple types of emails to // occupy // the same varaible. SimpleEmail etc can each be used directly. List<Email> emails = new ArrayList<Email>(); EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null, null, null, null); emails.add(new SimpleEmail(messagingService)); emails.add(new MultiPartEmail(messagingService)); emails.add(new HtmlEmail(messagingService)); try { listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = listenerSession.createQueue(emailQueueName); consumer = listenerSession.createConsumer(emailQueue); consumer.setMessageListener(new EmailListener()); listenerConn.start(); listenerSession.run(); } catch (JMSException e2) { e2.printStackTrace(); Assert.assertTrue(false); } Wiser smtpServer = new Wiser(); smtpServer.setPort(smtpTestPort); smtpServer.start(); try { clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = clientSession.createQueue(emailQueueName); producer = clientSession.createProducer(emailQueue); clientConn.start(); clientSession.run(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } for (Email em : emails) { try { em.addTo(TEST_EMAIL_TO); em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL); // host and port will be ignored since the email session is // established // by // the listener em.setHostName("localhost"); em.setSmtpPort(smtpTestPort); em.setSubject(TEST_EMAIL_SUBJECT); if (em instanceof HtmlEmail) { em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL); } else if (em instanceof MultiPartEmail) { em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL); } else if (em instanceof SimpleEmail) { em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL); } } catch (EmailException e1) { Assert.assertTrue(false); e1.printStackTrace(); } try { em.buildMimeMessage(); } catch (EmailException e1) { e1.printStackTrace(); Assert.assertTrue(false); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { em.getMimeMessage().writeTo(os); } catch (javax.mail.MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } String content = os.toString(); ObjectMessage om; try { om = clientSession.createObjectMessage(content); om.setJMSType(emailType); LOG.info("Client: Sending test message...."); producer.send(om); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } } long start = System.currentTimeMillis(); while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) { // wait for transport } Assert.assertTrue(listenerMessagesProcessed == 3); List<WiserMessage> messages = smtpServer.getMessages(); Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3); for (WiserMessage wisermsg : messages) { String body = null; String subject = null; MimeMessage testmail = null; try { testmail = wisermsg.getMimeMessage(); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } if (testmail != null) { LOG.info("SMTP server: test email received: "); try { LOG.info("To: " + testmail.getHeader("To", ",")); LOG.info("Subject: " + testmail.getHeader("Subject", ",")); body = getBodyAsString(testmail.getContent()); subject = testmail.getHeader("Subject", ","); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(false); e.printStackTrace(); } LOG.info("Body: " + body); Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT)); Assert.assertTrue(body.contains("This is a Commons")); } else { Assert.assertTrue(false); } } if (clientSession != null) { try { clientSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } clientSession = null; } if (listenerSession != null) { try { listenerSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } listenerSession = null; } smtpServer.stop(); }