List of usage examples for javax.mail.internet MimeMessage getAllHeaderLines
@Override public Enumeration<String> getAllHeaderLines() throws MessagingException
From source file:org.apache.james.server.core.MimeMessageUtil.java
/** * Calculate the size of the give mimeMessage * // www . j av a 2s . co m * @param message * the MimeMessage * @return size the calculated size * @throws MessagingException * if a problem occours while calculate the message size */ public static long calculateMessageSize(MimeMessage message) throws MessagingException { long size; // SK: Should probably eventually store this as a locally // maintained value (so we don't have to load and reparse // messages each time). size = message.getSize(); if (size != -1) { Enumeration<String> e = message.getAllHeaderLines(); if (e.hasMoreElements()) { size += 2; } while (e.hasMoreElements()) { // add 2 bytes for the CRLF size += e.nextElement().length() + 2; } } if (size == -1) { SizeCalculatorOutputStream out = new SizeCalculatorOutputStream(); try { message.writeTo(out); } catch (IOException e) { // should never happen as SizeCalculator does not actually throw // IOExceptions. throw new MessagingException("IOException wrapped by getMessageSize", e); } size = out.getSize(); } return size; }
From source file:org.apache.james.core.MimeMessageUtil.java
/** * Calculate the size of the give mimeMessage * //from w ww .ja va 2s . c om * @param message * the MimeMessage * @return size the calculated size * @throws MessagingException * if a problem occours while calculate the message size */ public static long calculateMessageSize(MimeMessage message) throws MessagingException { long size; // SK: Should probably eventually store this as a locally // maintained value (so we don't have to load and reparse // messages each time). size = message.getSize(); if (size != -1) { Enumeration<?> e = message.getAllHeaderLines(); if (e.hasMoreElements()) { size += 2; } while (e.hasMoreElements()) { // add 2 bytes for the CRLF size += ((String) e.nextElement()).length() + 2; } } if (size == -1) { SizeCalculatorOutputStream out = new SizeCalculatorOutputStream(); try { message.writeTo(out); } catch (IOException e) { // should never happen as SizeCalculator does not actually throw // IOExceptions. throw new MessagingException("IOException wrapped by getMessageSize", e); } size = out.getSize(); } return size; }
From source file:org.apache.james.transport.mailets.LogMessage.java
@SuppressWarnings("unchecked") private void logHeaders(MimeMessage message) throws MessagingException { if (headers) { log("\n"); for (String header : Collections.list((Enumeration<String>) message.getAllHeaderLines())) { log(header + "\n"); }//from www .ja v a 2 s. c om } }
From source file:org.apache.james.jdkim.mailets.DKIMSign.java
@SuppressWarnings("unchecked") private void prependHeader(MimeMessage message, String signatureHeader) throws MessagingException { List<String> prevHeader = new LinkedList<String>(); // read all the headers for (Enumeration<String> e = message.getAllHeaderLines(); e.hasMoreElements();) { String headerLine = e.nextElement(); prevHeader.add(headerLine);//w w w . j a v a 2 s . c o m } // remove all the headers for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) { Header header = e.nextElement(); message.removeHeader(header.getName()); } // add our header message.addHeaderLine(signatureHeader); // add the remaining headers using "addHeaderLine" that won't alter the // insertion order. for (Iterator<String> i = prevHeader.iterator(); i.hasNext();) { String header = i.next(); message.addHeaderLine(header); } }
From source file:com.zotoh.maedr.device.PopIO.java
private void getMsgs() throws Exception { int cnt = _fd.getMessageCount(); tlog().debug("PopIO: count of new messages: {}", cnt); if (cnt <= 0) return;// www . ja v a 2s. com StringBuilder hds = new StringBuilder(512); Message[] msgs = _fd.getMessages(); MimeMessage mm; StreamData data; String s; for (int i = 0; i < msgs.length; ++i) { mm = (MimeMessage) msgs[i]; //TODO //_fd.getUID(mm); // read all the header lines hds.setLength(0); for (Enumeration<?> en = mm.getAllHeaderLines(); en.hasMoreElements();) { s = (String) en.nextElement(); // if (s.toLowerCase().indexOf(CTL) >= 0) {} // else hds.append(s).append("\r\n"); } data = StreamUte.readStream(mm.getRawInputStream()); try { dispatch(new POP3Event(this, hds.toString(), data)); } finally { if (_delete) { mm.setFlag(Flags.Flag.DELETED, true); } } } }
From source file:eu.peppol.outbound.HttpPostTestIT.java
@Test public void testPost() throws Exception { InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader() .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML); assertNotNull(resourceAsStream,//from w ww.jav a 2 s . c o m "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path"); X509Certificate ourCertificate = keystoreManager.getOurCertificate(); SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(), ourCertificate); MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream, new MimeType("application/xml")); signedMimeMessage.writeTo(System.out); CloseableHttpClient httpClient = createCloseableHttpClient(); HttpPost httpPost = new HttpPost(OXALIS_AS2_URL); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); signedMimeMessage.writeTo(byteArrayOutputStream); X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal(); CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal); PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender); httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString()); httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(), new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST") .toString()); httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(), As2DispositionNotificationOptions.getDefault().toString()); httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION); httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE"); httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString()); httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date())); // Inserts the S/MIME message to be posted httpPost.setEntity( new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed"))); CloseableHttpResponse postResponse = null; // EXECUTE !!!! try { postResponse = httpClient.execute(httpPost); } catch (HttpHostConnectException e) { fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL); } HttpEntity entity = postResponse.getEntity(); // Any results? Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200); String contents = EntityUtils.toString(entity); assertNotNull(contents); if (log.isDebugEnabled()) { log.debug("Received: \n"); Header[] allHeaders = postResponse.getAllHeaders(); for (Header header : allHeaders) { log.debug("" + header.getName() + ": " + header.getValue()); } log.debug("\n" + contents); log.debug("---------------------------"); } try { MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents); System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType()); // Make sure we set content type header for the multipart message (should be multipart/signed) String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse); Enumeration<String> headerlines = mimeMessage.getAllHeaderLines(); while (headerlines.hasMoreElements()) { // Content-Type: multipart/signed; // protocol="application/pkcs7-signature"; // micalg=sha-1; // boundary="----=_Part_3_520186210.1399207766925" System.out.println("HeaderLine : " + headerlines.nextElement()); } MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); String msg = mdnMimeMessageInspector.getPlainTextPartAsText(); System.out.println(msg); } finally { postResponse.close(); } }
From source file:gov.nih.nci.cacis.nav.SendEncryptedMail.java
private MimeMessage encryptMessage(MimeMessage message, Session session, Certificate cert) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException, MessagingException, IOException {/*from w ww .j a v a2 s .com*/ /* Create the encrypter */ final SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); encrypter.addKeyTransRecipient((X509Certificate) cert); /* Encrypt the message */ final MimeBodyPart encryptedPart = encrypter.generate(message, SMIMEEnvelopedGenerator.AES256_CBC, PROVIDER_TYPE); /* * Create a new MimeMessage that contains the encrypted and signed content */ final ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); final MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray())); /* Set all original MIME headers in the encrypted message */ final Enumeration headers = message.getAllHeaderLines(); while (headers.hasMoreElements()) { final String headerLine = (String) headers.nextElement(); /* * Make sure not to override any content-* headers from the original message */ if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } return encryptedMessage; }
From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java
private void extractMimeMessageMetaInfo(MimeMessage message, PartContext context) throws MessagingException { TextExtractorContext extractorContext = new TextExtractorContextImpl(); extractorContext.setEncoding(CharEncoding.US_ASCII); extractorContext.setName("headers"); StrBuilder sb = new StrBuilder(4096); try {// w ww.jav a 2 s. c o m for (Enumeration<?> headerEnum = message.getAllHeaders(); headerEnum.hasMoreElements();) { Header header = (Header) headerEnum.nextElement(); if (header == null) { continue; } if (skipHeaders != null && skipHeaders.contains(StringUtils.lowerCase(header.getName()))) { continue; } sb.append(header.getName()).append(": ").appendln(HeaderUtils.decodeTextQuietly(header.getValue())); } } catch (MessagingException e) { /* * Fallback to raw headers */ for (Enumeration<?> headerEnum = message.getAllHeaderLines(); headerEnum.hasMoreElements();) { sb.appendln(headerEnum.nextElement()); } } byte[] headerBytes = MiscStringUtils.toUTF8Bytes(sb.toString()); RewindableInputStream input = new RewindableInputStream(new ByteArrayInputStream(headerBytes), MEM_THRESHOLD); ExtractedPart part = new ExtractedPartImpl(extractorContext, input, headerBytes.length); try { context.update(part, true /* add */); } catch (IOException e) { throw new MessagingException("Error adding part to context.", e); } }
From source file:org.sakaiproject.james.SakaiMailet.java
/** * Process incoming mail./* w ww . ja va 2 s .c om*/ * * @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:org.sakaiproject.email.impl.BasicEmailService.java
public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject, String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException { // some timing for debug long start = 0; if (M_log.isDebugEnabled()) start = System.currentTimeMillis(); // if in test mode, use the test method if (m_testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders); return;//from w w w . j a v a 2 s .c om } if (m_smtp == null) { M_log.error( "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties"); return; } if (from == null) { M_log.warn("sendMail: null from"); return; } if (to == null) { M_log.warn("sendMail: null to"); return; } if (content == null) { M_log.warn("sendMail: null content"); return; } Properties props = createMailSessionProperties(); Session session = Session.getInstance(props); // see if we have a message-id in the additional headers String mid = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) { // length of 'message-id: ' == 12 mid = header.substring(12); break; } } } // use the special extension that can set the id MimeMessage msg = new MyMessage(session, mid); // the FULL content-type header, for example: // Content-Type: text/plain; charset=windows-1252; format=flowed String contentTypeHeader = null; // If we need to force the container to use a certain multipart subtype // e.g. 'alternative' // then sneak it through in the additionalHeaders String multipartSubtype = null; // set the additional headers on the message // but treat Content-Type specially as we need to check the charset // and we already dealt with the message id if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": ")) contentTypeHeader = header; else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": ")) multipartSubtype = header.substring(header.indexOf(":") + 1).trim(); else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) msg.addHeaderLine(header); } } // date if (msg.getHeader(EmailHeaders.DATE) == null) msg.setSentDate(new Date(System.currentTimeMillis())); // set the message sender msg.setFrom(from); // set the message recipients (headers) setRecipients(headerTo, msg); // set the reply to if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null)) msg.setReplyTo(replyTo); // update to be Postmaster if necessary checkFrom(msg); // figure out what charset encoding to use // // first try to use the charset from the forwarded // Content-Type header (if there is one). // // if that charset doesn't work, try a couple others. // the character set, for example, windows-1252 or UTF-8 String charset = extractCharset(contentTypeHeader); if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) { // use the charset from the Content-Type header } else if (canUseCharset(content, CharacterSet.ISO_8859_1) && canUseCharset(subject, CharacterSet.ISO_8859_1)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1; charset = CharacterSet.ISO_8859_1; } else if (canUseCharset(content, CharacterSet.WINDOWS_1252) && canUseCharset(subject, CharacterSet.WINDOWS_1252)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252; charset = CharacterSet.WINDOWS_1252; } else { // catch-all - UTF-8 should be able to handle anything if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.UTF_8; else contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset=" + CharacterSet.UTF_8; charset = CharacterSet.UTF_8; } if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null)) msg.setSubject(subject, charset); // extract just the content type value from the header String contentType = null; if (contentTypeHeader != null) { int colonPos = contentTypeHeader.indexOf(":"); contentType = contentTypeHeader.substring(colonPos + 1).trim(); } setContent(content, attachments, msg, contentType, charset, multipartSubtype); // if we have a full Content-Type header, set it NOW // (after setting the body of the message so that format=flowed is preserved) // if there attachments, the messsage type will default to multipart/mixed and should // stay that way. if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) { msg.addHeaderLine(contentTypeHeader); msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable"); } if (M_log.isDebugEnabled()) { M_log.debug("HeaderLines received were: "); Enumeration<String> allHeaders = msg.getAllHeaderLines(); while (allHeaders.hasMoreElements()) { M_log.debug((String) allHeaders.nextElement()); } } sendMessageAndLog(from, to, subject, headerTo, start, msg, session); }