List of usage examples for javax.mail.internet MimeMessage getMessageID
public String getMessageID() throws MessagingException
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testProtectedHeadersMailAttributes() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailetConfig.setInitParameter("retainMessageID", "false"); mailet.init(mailetConfig);/* ww w . j a v a 2s .c o m*/ Mail mail = new MockMail(); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); /* * set protected headers in the mail attributes */ mailAttributes.setProtectedHeaders(new String[] { "from", "message-id" }); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); mailAttributes.setCertificates(certificates); mailet.service(mail); MimeMessage encrypted = mail.getMessage(); /* * Change from to see whether it was protected */ encrypted.setFrom(new InternetAddress("changed@changed.example.com")); MailUtils.validateMessage(encrypted); assertFalse("<123456>".equals(encrypted.getMessageID())); assertEquals(SMIMEHeader.ENCRYPTED_CONTENT_TYPE, encrypted.getContentType()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(encrypted, keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); /* * now decrypt and check whether message-id and from was protected */ MimeMessage decrypted = inspector.getContentAsMimeMessage(); inspector = new SMIMEInspectorImpl(decrypted, keyStore, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); assertTrue("<123456>".equals(decrypted.getMessageID())); assertEquals("test@example.com", StringUtils.join(decrypted.getFrom())); }
From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java
@Test public void testRetainMessageID() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMESign mailet = new SMIMESign(); mailet.init(mailetConfig);//w w w.ja v a 2 s .co m MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE, SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType()); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC"); assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType()); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(mail.getMessage())); assertEquals(3, inspector.getSignedInspector().getCertificates().size()); assertEquals("1C1C1CF46CC9233B23391A3B9BEF558969567091", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(0), Digest.SHA1)); assertEquals("D8F8E5B92E651B1E3EF93B5493EACDE4C13AFEE0", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(1), Digest.SHA1)); assertEquals("69D7FFAF26BD5E9E4F42083BCA077BFAA8398593", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(2), Digest.SHA1)); assertEquals(1, inspector.getSignedInspector().getSigners().size()); assertEquals(Digest.SHA1.getOID(), inspector.getSignedInspector().getSigners().get(0).getDigestAlgorithmOID()); assertEquals("<123456>", mail.getMessage().getMessageID()); }
From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java
@Test public void testNewMessageID() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMESign mailet = new SMIMESign(); mailetConfig.setInitParameter("retainMessageID", "false"); mailet.init(mailetConfig);// w ww .ja va 2 s.co m MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE, SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType()); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC"); assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType()); assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(mail.getMessage())); assertEquals(3, inspector.getSignedInspector().getCertificates().size()); assertEquals("1C1C1CF46CC9233B23391A3B9BEF558969567091", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(0), Digest.SHA1)); assertEquals("D8F8E5B92E651B1E3EF93B5493EACDE4C13AFEE0", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(1), Digest.SHA1)); assertEquals("69D7FFAF26BD5E9E4F42083BCA077BFAA8398593", X509CertificateInspector .getThumbprint(inspector.getSignedInspector().getCertificates().get(2), Digest.SHA1)); assertEquals(1, inspector.getSignedInspector().getSigners().size()); assertEquals(Digest.SHA1.getOID(), inspector.getSignedInspector().getSigners().get(0).getDigestAlgorithmOID()); assertFalse("<123456>".equals(mail.getMessage().getMessageID())); assertTrue(mail.getMessage().getMessageID().contains("JavaMail")); }
From source file:com.zimbra.cs.imap.ImapMessage.java
static void serializeEnvelope(PrintStream ps, MimeMessage mm) throws MessagingException { // 7.4.2: "The fields of the envelope structure are in the following order: date, subject, // from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id. The date, // subject, in-reply-to, and message-id fields are strings. The from, sender, // reply-to, to, cc, and bcc fields are parenthesized lists of address structures." InternetAddress[] from = Mime.parseAddressHeader(mm, "From", false); InternetAddress[] sender = Mime.parseAddressHeader(mm, "Sender", false), replyTo = Mime.parseAddressHeader(mm, "Reply-To", false); ps.write('('); nstring(ps, mm.getHeader("Date", ",")); ps.write(' '); nstring2047(ps, Mime.getSubject(mm)); ps.write(' '); naddresses(ps, from);//from w ww . j av a 2 s . co m ps.write(' '); naddresses(ps, sender.length == 0 ? from : sender); ps.write(' '); naddresses(ps, replyTo.length == 0 ? from : replyTo); ps.write(' '); naddresses(ps, Mime.parseAddressHeader(mm, "To", false)); ps.write(' '); naddresses(ps, Mime.parseAddressHeader(mm, "CC", false)); ps.write(' '); naddresses(ps, Mime.parseAddressHeader(mm, "BCC", false)); ps.write(' '); nstring(ps, mm.getHeader("In-Reply-To", " ")); ps.write(' '); nstring(ps, mm.getMessageID()); ps.write(')'); }
From source file:org.sakaiproject.james.SakaiMailet.java
/** * Process incoming mail.//from ww w . j a v a 2 s.co m * * @param mail * ... */ public void service(Mail mail) throws MessagingException { // get the postmaster user User postmaster = null; try { postmaster = userDirectoryService.getUser(POSTMASTER); } catch (UserNotDefinedException e) { M_log.warn("service(): no postmaster, incoming mail will not be processed until a postmaster user (id=" + POSTMASTER + ") exists in this Sakai instance"); mail.setState(Mail.GHOST); return; } try { // set the current user to postmaster Session s = sessionManager.getCurrentSession(); if (s != null) { s.setUserId(postmaster.getId()); } else { M_log.warn( "service - no SessionManager.getCurrentSession, cannot set to postmaser user, attempting to use the current user (" + sessionManager.getCurrentSessionUserId() + ") and session (" + sessionManager.getCurrentSession().getId() + ")"); } MimeMessage msg = mail.getMessage(); String id = msg.getMessageID(); Address[] fromAddresses = msg.getFrom(); String from = null; String fromAddr = null; if ((fromAddresses != null) && (fromAddresses.length == 1)) { from = fromAddresses[0].toString(); if (fromAddresses[0] instanceof InternetAddress) { fromAddr = ((InternetAddress) (fromAddresses[0])).getAddress(); } } else { from = mail.getSender().toString(); fromAddr = mail.getSender().toInternetAddress().getAddress(); } Collection<MailAddress> to = mail.getRecipients(); Date sent = msg.getSentDate(); String subject = StringUtils.trimToNull(msg.getSubject()); Enumeration<String> headers = msg.getAllHeaderLines(); List<String> mailHeaders = new Vector<String>(); while (headers.hasMoreElements()) { String line = (String) headers.nextElement(); // check if string starts with "Content-Type", ignoring case if (line.regionMatches(true, 0, MailArchiveService.HEADER_CONTENT_TYPE, 0, MailArchiveService.HEADER_CONTENT_TYPE.length())) { String contentType = line.substring(0, MailArchiveService.HEADER_CONTENT_TYPE.length()); mailHeaders.add(line.replaceAll(contentType, MailArchiveService.HEADER_OUTER_CONTENT_TYPE)); } // don't copy null subject lines. we'll add a real one below if (!(line.regionMatches(true, 0, MailArchiveService.HEADER_SUBJECT, 0, MailArchiveService.HEADER_SUBJECT.length()) && subject == null)) mailHeaders.add(line); } //Add headers for a null subject, keep null in DB if (subject == null) { mailHeaders.add(MailArchiveService.HEADER_SUBJECT + ": <" + rb.getString("err_no_subject") + ">"); } if (M_log.isDebugEnabled()) { M_log.debug(id + " : mail: from:" + from + " sent: " + timeService.newTime(sent.getTime()).toStringLocalFull() + " subject: " + subject); } // process for each recipient Iterator<MailAddress> it = to.iterator(); while (it.hasNext()) { String mailId = null; try { MailAddress recipient = (MailAddress) it.next(); if (M_log.isDebugEnabled()) { M_log.debug(id + " : checking to: " + recipient); } // the recipient's mail id mailId = recipient.getUser(); // eat the no-reply if ("no-reply".equalsIgnoreCase(mailId)) { mail.setState(Mail.GHOST); if (M_log.isInfoEnabled()) { M_log.info("Incoming message mailId (" + mailId + ") set to no-reply, mail processing cancelled"); } /* NOTE: this doesn't make a lot of sense to me, once the mail is ghosted * then it won't be processed anymore so continuing is kind of a waste of time, * shouldn't this just break instead? */ continue; } // find the channel (mailbox) that this is addressed to // for now, check only for it being a site or alias to a site. // %%% - add user and other later -ggolden MailArchiveChannel channel = null; // first, assume the mailId is a site id String channelRef = MailArchiveService.channelReference(mailId, SiteService.MAIN_CONTAINER); try { channel = MailArchiveService.getMailArchiveChannel(channelRef); if (M_log.isDebugEnabled()) { M_log.debug( "Incoming message mailId (" + mailId + ") IS a valid site channel reference"); } } catch (IdUnusedException goOn) { // INDICATES the incoming message is NOT for a currently valid site if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") is NOT a valid site channel reference, will attempt more matches"); } } catch (PermissionException e) { // INDICATES the channel is valid but the user has no permission to access it // This generally should not happen because the current user should be the postmaster M_log.warn( "mailarchive failure: message processing cancelled: PermissionException with channelRef (" + channelRef + ") - user not allowed to get this mail archive channel: (id=" + id + ") (mailId=" + mailId + ") (user=" + sessionManager.getCurrentSessionUserId() + ") (session=" + sessionManager.getCurrentSession().getId() + "): " + e, e); // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } // next, if not a site, see if it's an alias to a site or channel if (channel == null) { // if not an alias, it will throw the IdUnusedException caught below Reference ref = entityManager.newReference(aliasService.getTarget(mailId)); if (ref.getType().equals(SiteService.APPLICATION_ID)) { // ref is a site // now we have a site reference, try for it's channel channelRef = MailArchiveService.channelReference(ref.getId(), SiteService.MAIN_CONTAINER); if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid site reference (" + ref.getId() + ")"); } } else if (ref.getType().equals(MailArchiveService.APPLICATION_ID)) { // ref is a channel channelRef = ref.getReference(); if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid channel reference (" + ref.getId() + ")"); } } else { // ref cannot be be matched if (M_log.isInfoEnabled()) { M_log.info(id + " : mail rejected: unknown address: " + mailId + " : mailId (" + mailId + ") does NOT match site, alias, or other current channel"); } if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") is NOT a valid does NOT match site, alias, or other current channel reference (" + ref.getId() + "), message rejected"); } throw new IdUnusedException(mailId); } // if there's no channel for this site, it will throw the IdUnusedException caught below try { channel = MailArchiveService.getMailArchiveChannel(channelRef); } catch (PermissionException e) { // INDICATES the channel is valid but the user has no permission to access it // This generally should not happen because the current user should be the postmaster M_log.warn( "mailarchive failure: message processing cancelled: PermissionException with channelRef (" + channelRef + ") - user not allowed to get this mail archive channel: (id=" + id + ") (mailId=" + mailId + ") (user=" + sessionManager.getCurrentSessionUserId() + ") (session=" + sessionManager.getCurrentSession().getId() + "): " + e, e); // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + ") IS a valid channel (" + channelRef + "), found channel: " + channel); } } if (channel == null) { if (M_log.isDebugEnabled()) { M_log.debug("Incoming message mailId (" + mailId + "), channelRef (" + channelRef + ") could not be resolved and is null: " + channel); } // this should never happen but it is here just in case throw new IdUnusedException(mailId); } // skip disabled channels if (!channel.getEnabled()) { // INDICATES that the channel is NOT currently enabled so no messages can be received if (from.startsWith(POSTMASTER)) { mail.setState(Mail.GHOST); } else { // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_email_off") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(courseMailArchiveDisabledProcessor); } if (M_log.isInfoEnabled()) { M_log.info( id + " : mail rejected: channel (" + channelRef + ") not enabled: " + mailId); } continue; } // for non-open channels, make sure the from is a member if (!channel.getOpen()) { // see if our fromAddr is the email address of any of the users who are permitted to add messages to the channel. if (!fromValidUser(fromAddr, channel)) { // INDICATES user is not allowed to send messages to this group if (M_log.isInfoEnabled()) { M_log.info(id + " : mail rejected: from: " + fromAddr + " not authorized for site: " + mailId + " and channel (" + channelRef + ")"); } // BOUNCE REPLY - send a message back to the user to let them know their email failed String errMsg = rb.getString("err_not_member") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(userNotAllowedToPostProcessor); continue; } } // prepare the message StringBuilder bodyBuf[] = new StringBuilder[2]; bodyBuf[0] = new StringBuilder(); bodyBuf[1] = new StringBuilder(); List<Reference> attachments = entityManager.newReferenceList(); String siteId = null; if (siteService.siteExists(channel.getContext())) { siteId = channel.getContext(); } try { StringBuilder bodyContentType = new StringBuilder(); parseParts(siteId, msg, id, bodyBuf, bodyContentType, attachments, Integer.valueOf(-1)); if (bodyContentType.length() > 0) { // save the content type of the message body - which may be different from the // overall MIME type of the message (multipart, etc) mailHeaders.add(MailArchiveService.HEADER_INNER_CONTENT_TYPE + ": " + bodyContentType); } } catch (MessagingException e) { // NOTE: if this happens it just means we don't get the extra header, not the end of the world //e.printStackTrace(); M_log.warn("MessagingException: service(): msg.getContent() threw: " + e, e); } catch (IOException e) { // NOTE: if this happens it just means we don't get the extra header, not the end of the world //e.printStackTrace(); M_log.warn("IOException: service(): msg.getContent() threw: " + e, e); } mailHeaders.add("List-Id: <" + channel.getId() + "." + channel.getContext() + "." + serverConfigurationService.getServerName() + ">"); // post the message to the group's channel String body[] = new String[2]; body[0] = bodyBuf[0].toString(); // plain/text body[1] = bodyBuf[1].toString(); // html/text try { if (channel.getReplyToList()) { List<String> modifiedHeaders = new Vector<String>(); for (String header : (List<String>) mailHeaders) { if (header != null && !header.startsWith("Reply-To:")) { modifiedHeaders.add(header); } } // Note: can't use recipient, since it's host may be configured as mailId@myhost.james String mailHost = serverConfigurationService.getServerName(); if (mailHost == null || mailHost.trim().equals("")) mailHost = mail.getRemoteHost(); MailAddress replyTo = new MailAddress(mailId, mailHost); if (M_log.isDebugEnabled()) { M_log.debug("Set Reply-To address to " + replyTo.toString()); } modifiedHeaders.add("Reply-To: " + replyTo.toString()); // post the message to the group's channel channel.addMailArchiveMessage(subject, from.toString(), timeService.newTime(sent.getTime()), modifiedHeaders, attachments, body); } else { // post the message to the group's channel channel.addMailArchiveMessage(subject, from.toString(), timeService.newTime(sent.getTime()), mailHeaders, attachments, body); } } catch (PermissionException pe) { // INDICATES that the current user does not have permission to add or get the mail archive message from the current channel // This generally should not happen because the current user should be the postmaster M_log.warn("mailarchive PermissionException message service failure: (id=" + id + ") (mailId=" + mailId + ") : " + pe, pe); mail.setState(Mail.GHOST); // ghost out the message because this should not happen } if (M_log.isDebugEnabled()) { M_log.debug(id + " : delivered to:" + mailId); } // all is happy - ghost the message to stop further processing mail.setState(Mail.GHOST); } catch (IdUnusedException goOn) { // INDICATES that the channelReference found above was actually invalid OR that no channel reference could be identified // if this is to the postmaster, and there's no site, channel or alias for the postmaster, then quietly eat the message if (POSTMASTER.equals(mailId) || from.startsWith(POSTMASTER + "@")) { mail.setState(Mail.GHOST); continue; } // BOUNCE REPLY - send a message back to the user to let them know their email failed if (M_log.isInfoEnabled()) { M_log.info("mailarchive invalid or unusable channel reference (" + mailId + "): " + id + " : mail rejected: " + goOn.toString()); } String errMsg = rb.getString("err_addr_unknown") + "\n\n"; String mailSupport = StringUtils .trimToNull(serverConfigurationService.getString("mail.support")); if (mailSupport != null) { errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport }) + "\n"; } mail.setErrorMessage(errMsg); mail.setState(courseMailArchiveNotExistsProcessor); } catch (Exception ex) { // INDICATES that some general exception has occurred which we did not expect // This definitely should NOT happen M_log.error("mailarchive General message service exception: (id=" + id + ") (mailId=" + mailId + ") : " + ex, ex); mail.setState(Mail.GHOST); // ghost the message to stop it from being further processed } } } finally { // clear out any current current bindings threadLocalManager.clear(); } }
From source file:hudson.tasks.MailSender.java
public boolean execute(AbstractBuild<?, ?> build, BuildListener listener) throws InterruptedException { try {//w w w . j a va 2 s . c o m MimeMessage mail = getMail(build, listener); if (mail != null) { // if the previous e-mail was sent for a success, this new e-mail // is not a follow up AbstractBuild<?, ?> pb = build.getPreviousBuild(); if (pb != null && pb.getResult() == Result.SUCCESS) { mail.removeHeader("In-Reply-To"); mail.removeHeader("References"); } Address[] allRecipients = mail.getAllRecipients(); if (allRecipients != null) { StringBuilder buf = new StringBuilder("Sending e-mails to:"); for (Address a : allRecipients) buf.append(' ').append(a); listener.getLogger().println(buf); Transport.send(mail); build.addAction(new MailMessageIdAction(mail.getMessageID())); } else { listener.getLogger().println(Messages.MailSender_ListEmpty()); } } } catch (MessagingException e) { e.printStackTrace(listener.error(e.getMessage())); } catch (UnsupportedEncodingException e) { e.printStackTrace(listener.error(e.getMessage())); } finally { CHECKPOINT.report(); } return true; }
From source file:edu.stanford.muse.util.EmailUtils.java
/** * best effort to toString something about the given message. * use only for diagnostics, not for user-visible messages. * treads defensively, this can be called to report on a badly formatted message. *///from w ww .jav a 2s .c o m public static String formatMessageHeader(MimeMessage m) throws MessagingException { StringBuilder sb = new StringBuilder(); sb.append("To: "); if (m == null) { log.warn("Trying to format null message!?"); return "Null message"; } try { Address[] tos = m.getAllRecipients(); if (tos != null) for (Address a : tos) sb.append(a.toString() + " "); sb.append("\n"); } catch (Exception e) { Util.print_exception(e, log); } sb.append("From: "); try { Address[] froms = m.getFrom(); if (froms != null) for (Address a : froms) sb.append(a.toString() + " "); sb.append("\n"); } catch (Exception e) { Util.print_exception(e, log); } try { sb.append("Subject: " + m.getSubject()); sb.append("Message-ID: " + m.getMessageID()); } catch (Exception e) { Util.print_exception(e, log); } return sb.toString(); }
From source file:davmail.smtp.TestSmtp.java
public void sendAndCheckMessage(MimeMessage mimeMessage, String from, String bcc) throws IOException, MessagingException, InterruptedException { // generate message id mimeMessage.saveChanges();//from w ww. j a v a 2 s . c om // mimeMessage.writeTo(System.out); // copy Message-id to references header mimeMessage.addHeader("references", mimeMessage.getHeader("message-id")[0]); if (from != null) { writeLine("MAIL FROM:" + from); } else { writeLine("MAIL FROM:" + session.getEmail()); } readLine(); if (bcc != null) { writeLine("RCPT TO:" + bcc); readLine(); } writeLine("RCPT TO:" + Settings.getProperty("davmail.to")); readLine(); writeLine("DATA"); assertEquals("354 Start mail input; end with <CRLF>.<CRLF>", readLine()); mimeMessage.writeTo(new DoubleDotOutputStream(socketOutputStream)); writeLine(""); writeLine("."); assertEquals("250 Queued mail for delivery", readLine()); // wait for asynchronous message send ExchangeSession.MessageList messages = null; for (int i = 0; i < 5; i++) { messages = session.searchMessages("Sent", session.headerIsEqualTo("references", mimeMessage.getMessageID())); if (messages.size() > 0) { break; } Thread.sleep(1000); } assertEquals(1, messages.size()); ExchangeSession.Message sentMessage = messages.get(0); sentMessage.getMimeMessage().writeTo(System.out); assertEquals(mimeMessage.getDataHandler().getContent(), sentMessage.getMimeMessage().getDataHandler().getContent()); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncrypt.java
@Override public void serviceMail(Mail mail) { try {/*from w w w. j av a 2 s .c om*/ DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); Certificates certificateStore = mailAttributes.getCertificates(); if (certificateStore != null) { Collection<X509Certificate> certificates = certificateStore.getCertificates(); if (certificates.size() > 0) { MimeMessage message = mail.getMessage(); if (message != null) { SMIMEBuilder sMIMEBuilder = new SMIMEBuilderImpl(message, getProtectedHeaders(mail)); sMIMEBuilder.setUseDeprecatedContentTypes(useDeprecatedContentTypes); for (X509Certificate certificate : certificates) { sMIMEBuilder.addRecipient(certificate, getRecipientMode()); } SMIMEEncryptionAlgorithm localAlgorithm = getEncryptionAlgorithm(mail); int localKeySize = (keySize != null ? keySize : localAlgorithm.defaultKeySize()); getLogger().debug("Encrypting the message. Encryption algorithm: {}, key size: {}", localAlgorithm, localKeySize); sMIMEBuilder.encrypt(localAlgorithm, localKeySize); MimeMessage encrypted = sMIMEBuilder.buildMessage(); if (encrypted != null) { encrypted.saveChanges(); /* * A new MimeMessage instance will be created. This makes ure that the * MimeMessage can be written by James (using writeTo()). The message-ID * of the source message will be retained if told to do so */ encrypted = retainMessageID ? new MimeMessageWithID(encrypted, message.getMessageID()) : new MimeMessage(encrypted); mail.setMessage(encrypted); } } else { getLogger().warn("Message is null."); } } else { getLogger().warn("Certificate collection is empty."); } } else { getLogger().warn("Certificates attribute not found."); } } catch (SMIMEBuilderException e) { getLogger().error("Error encrypting the message.", e); } catch (MessagingException e) { getLogger().error("Error reading the message.", e); } catch (IOException e) { getLogger().error("IOException.", e); } }
From source file:com.duroty.service.Mailet.java
/** * DOCUMENT ME!// w w w . j a v a2s . c om * * @param id DOCUMENT ME! * @param mime DOCUMENT ME! * * @return DOCUMENT ME! */ private String getParentId(String id, MimeMessage mime) { String references = null; try { if (references == null) { String[] aux = mime.getHeader(RFC2822Headers.REFERENCES); //Cal controlar que portem un array if ((aux != null) && (aux.length > 0)) { if (aux[0] != null) { String[] ref = aux[0].split("\\s+"); if ((ref != null) && (ref.length > 1)) { references = ref[0]; } } if (references == null) { references = aux[0]; } } } if (references == null) { String[] aux = mime.getHeader(RFC2822Headers.IN_REPLY_TO); //Cal veure que portem un array if ((aux != null) && (aux.length > 0)) { references = aux[0]; } } if (references == null) { references = mime.getMessageID(); mime.addHeader(RFC2822Headers.IN_REPLY_TO, references); mime.addHeader(RFC2822Headers.REFERENCES, references); } } catch (MessagingException e) { references = null; } return references; }