List of usage examples for javax.mail.internet MimeMessage getHeader
@Override public String[] getHeader(String name) throws MessagingException
From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java
private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException { MimeMessage mail = (MimeMessage) part; Address[] adresses;/* www . j ava 2 s. c o m*/ if ((adresses = mail.getFrom()) != null && adresses.length > 0) { String from = adresses[0].toString(); // check if we should ignore this sender for (String ignore : this.ignoreFrom) { if (from.toLowerCase().contains(ignore)) { LOG.info("Ignoring email from " + from); return false; } } row.put(FROM, from); row.put(FROM_CLEAN, cleanAddress(from)); } else { return false; } List<String> to = new ArrayList<String>(); if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) { addAddressToList(adresses, to); } if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) { addAddressToList(adresses, to); } if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) { addAddressToList(adresses, to); } if (!to.isEmpty()) { row.put(TO_CC_BCC, to); List<String> cleanAddresses = cleanAddresses(to); row.put(TO_CC_BCC_CLEAN, cleanAddresses); // save first TO address into separate field row.put(TO, to.get(0)); row.put(TO_CLEAN, cleanAddresses.get(0)); } row.put(MESSAGE_ID, mail.getMessageID()); row.put(SUBJECT, mail.getSubject()); { Date d = mail.getSentDate(); if (d != null) { row.put(SENT_DATE, d); } } { Date d = mail.getReceivedDate(); if (d != null) { row.put(RECEIVED_DATE, d); } } List<String> flags = new ArrayList<String>(); for (Flags.Flag flag : mail.getFlags().getSystemFlags()) { if (flag == Flags.Flag.ANSWERED) { flags.add(FLAG_ANSWERED); } else if (flag == Flags.Flag.DELETED) { flags.add(FLAG_DELETED); } else if (flag == Flags.Flag.DRAFT) { flags.add(FLAG_DRAFT); } else if (flag == Flags.Flag.FLAGGED) { flags.add(FLAG_FLAGGED); } else if (flag == Flags.Flag.RECENT) { flags.add(FLAG_RECENT); } else if (flag == Flags.Flag.SEEN) { flags.add(FLAG_SEEN); } } flags.addAll(Arrays.asList(mail.getFlags().getUserFlags())); row.put(FLAGS, flags); String[] hdrs = mail.getHeader("X-Mailer"); if (hdrs != null) { row.put(XMAILER, hdrs[0]); } return true; }
From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java
private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException { MimeMessage mail = (MimeMessage) part; Address[] adresses;// w w w.j a v a2s. co m if ((adresses = mail.getFrom()) != null && adresses.length > 0) { String from = adresses[0].toString(); // check if we should ignore this sender for (String ignore : this.ignoreFrom) { if (from.toLowerCase().contains(ignore)) { LOG.info("Ignoring email from " + from); return false; } } row.put(FROM, from); row.put(FROM_CLEAN, cleanAddress(from)); } else { return false; } List<String> to = new ArrayList<String>(); if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) { addAddressToList(adresses, to); } if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) { addAddressToList(adresses, to); } if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) { addAddressToList(adresses, to); } if (!to.isEmpty()) { row.put(TO_CC_BCC, to); List<String> cleanAddresses = cleanAddresses(to); row.put(TO_CC_BCC_CLEAN, cleanAddresses); // save first TO address into separate field row.put(TO, to.get(0)); row.put(TO_CLEAN, cleanAddresses.get(0)); } row.put(MESSAGE_ID, mail.getMessageID()); row.put(SUBJECT, mail.getSubject()); { Date d = mail.getSentDate(); if (d != null) { row.put(SENT_DATE, d); } } { Date d = mail.getReceivedDate(); if (d != null) { row.put(RECEIVED_DATE, d); } } List<String> flags = new ArrayList<String>(); for (Flags.Flag flag : mail.getFlags().getSystemFlags()) { if (flag == Flags.Flag.ANSWERED) { flags.add(FLAG_ANSWERED); } else if (flag == Flags.Flag.DELETED) { flags.add(FLAG_DELETED); } else if (flag == Flags.Flag.DRAFT) { flags.add(FLAG_DRAFT); } else if (flag == Flags.Flag.FLAGGED) { flags.add(FLAG_FLAGGED); } else if (flag == Flags.Flag.RECENT) { flags.add(FLAG_RECENT); } else if (flag == Flags.Flag.SEEN) { flags.add(FLAG_SEEN); } } flags.addAll(Arrays.asList(mail.getFlags().getUserFlags())); row.put(FLAGS, flags); String[] hdrs = mail.getHeader("X-Mailer"); if (hdrs != null) { row.put(XMAILER, hdrs[0]); } return true; }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static String getPriority(MimeMessage msg) throws MessagingException { String priority = "Normal"; String[] headers = msg.getHeader("X-Priority"); if (headers != null) { String headerPriority = headers[0]; if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1) priority = "Urgent"; else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1) priority = "NonUrgent"; else/*from w ww. j a va 2 s. c om*/ priority = "Normal"; } return priority; }
From source file:org.masukomi.aspirin.core.Bouncer.java
/** * This generates a response to the Return-Path address, or the address of * the message's sender if the Return-Path is not available. Note that this * is different than a mail-client's reply, which would use the Reply-To or * From header.//www .j av a2 s .co m * * @param mail * DOCUMENT ME! * @param message * DOCUMENT ME! * @param bouncer * DOCUMENT ME! * * @throws MessagingException * DOCUMENT ME! */ static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer) throws MessagingException { if (bouncer != null) { if (log.isDebugEnabled()) { log.debug("bouncing message to postmaster"); } MimeMessage orig = mail.getMessage(); //Create the reply message MimeMessage reply = (MimeMessage) orig.reply(false); //If there is a Return-Path header, if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) { //Return the message to that address, not to the Reply-To // address reply.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0])); } //Create the list of recipients in our MailAddress format Collection recipients = new HashSet(); Address[] addresses = reply.getAllRecipients(); for (int i = 0; i < addresses.length; i++) { recipients.add(new MailAddress((InternetAddress) addresses[i])); } //Change the sender... reply.setFrom(bouncer.toInternetAddress()); try { //Create the message body MimeMultipart multipart = new MimeMultipart(); //Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(message, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); //Add the original message as the second mime body part part = new MimeBodyPart(); part.setContent(orig.getContent(), orig.getContentType()); part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType()); multipart.addBodyPart(part); reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date())); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); } catch (IOException ioe) { throw new MessagingException("Unable to create multipart body", ioe); } //Send it off... //sendMail( bouncer, recipients, reply ); que.queMail(reply); } }
From source file:org.mule.transport.email.MailMuleMessageFactory.java
protected void addRecipientProperty(MuleMessage muleMessage, Message mailMessage, RecipientType recipientType, String property) throws MessagingException { MimeMessage mimeMessage = null; if (mailMessage instanceof MimeMessage) { mimeMessage = (MimeMessage) mailMessage; }/*from w ww . j ava2 s. com*/ try { Address[] recipients = mailMessage.getRecipients(recipientType); muleMessage.setProperty(property, MailUtils.mailAddressesToString(recipients), PropertyScope.INBOUND); } catch (MessagingException e) { if (mimeMessage != null) { String[] header = mimeMessage.getHeader(recipientType.toString()); String recipients = StringUtils.join(header, ", "); muleMessage.setProperty(property, recipients, PropertyScope.INBOUND); } } }
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;/* w w w. j av a 2s.co m*/ } 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); }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
/** * fix up From and ReplyTo if we need it to be from Postmaster *//*from w w w .j a v a 2 s. c om*/ private void checkFrom(MimeMessage msg) { String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true"); String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null); InternetAddress from = null; InternetAddress[] replyTo = null; try { Address[] fromA = msg.getFrom(); if (fromA == null || fromA.length == 0) { M_log.info("message from missing"); return; } else if (fromA.length > 1) { M_log.info("message from more than 1"); return; } else if (fromA instanceof InternetAddress[]) { from = (InternetAddress) fromA[0]; } else { M_log.info("message from not InternetAddress"); return; } Address[] replyToA = msg.getReplyTo(); if (replyToA == null) replyTo = null; else if (replyToA instanceof InternetAddress[]) replyTo = (InternetAddress[]) replyToA; else { M_log.info("message replyto isn't internet address"); return; } // should we replace from address with a Sakai address? if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) { // exceptions -- addresses to leave alone. Our own addresses are always exceptions. // you can also configure a regexp of exceptions. if (!from.getAddress().toLowerCase() .endsWith("@" + serverConfigurationService.getServerName().toLowerCase()) && (sendExceptions == null || sendExceptions.equals("") || !from.getAddress().toLowerCase().matches(sendExceptions))) { // not an exception. do the replacement. // First, decide on the replacement address. The config variable // may be the replacement address. If not, use postmaster if (sendFromSakai.indexOf("@") < 0) sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName(); // put the original from into reply-to, unless a replyto exists if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) { replyTo = new InternetAddress[1]; replyTo[0] = from; msg.setReplyTo(replyTo); } // for some reason setReplyTo doesn't work, though setFrom does. Have to create the // actual header line if (msg.getHeader(EmailHeaders.REPLY_TO) == null) msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress()); // and use the new from address // biggest issue is the "personal address", i.e. the comment text String origFromText = from.getPersonal(); String origFromAddress = from.getAddress(); String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT, "{}"); String fromText = null; if (origFromText != null && !origFromText.equals("")) fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")"); else fromText = fromTextPattern.replace("{}", origFromAddress); from = new InternetAddress(sendFromSakai); try { from.setPersonal(fromText); } catch (Exception e) { } msg.setFrom(from); } } } catch (javax.mail.internet.AddressException e) { M_log.info("checkfrom address exception " + e); } catch (javax.mail.MessagingException e) { M_log.info("checkfrom messaging exception " + e); } }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
protected void setRecipients(Map<RecipientType, InternetAddress[]> headerTo, MimeMessage msg) throws MessagingException { if (headerTo != null) { if (msg.getHeader(EmailHeaders.TO) == null && headerTo.containsKey(RecipientType.TO)) { msg.setRecipients(Message.RecipientType.TO, headerTo.get(RecipientType.TO)); }/* ww w. j av a 2 s. c o m*/ if (msg.getHeader(EmailHeaders.CC) == null && headerTo.containsKey(RecipientType.CC)) { msg.setRecipients(Message.RecipientType.CC, headerTo.get(RecipientType.CC)); } if (headerTo.containsKey(RecipientType.BCC)) { msg.setRecipients(Message.RecipientType.BCC, headerTo.get(RecipientType.BCC)); } } }
From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java
/** * Process an email, extracting attachments and constructing a Message. * @param mail the email to be processed. * @param mailingList the mailing list it is going to be affected to. * @param event the event which will be send at the end of all processing. * @throws MessagingException// w w w. ja va 2s . c o m * @throws IOException */ public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event) throws MessagingException, IOException { String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress(); if (!mailingList.checkSender(sender)) { return; } Message message = new Message(); message.setComponentId(mailingList.getComponentId()); message.setSender(sender); message.setSentDate(mail.getSentDate()); message.setMessageId(mail.getMessageID()); String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO); if (referenceId == null || referenceId.length == 0) { referenceId = mail.getHeader(MAIL_HEADER_REFERENCES); } if (referenceId == null || referenceId.length == 0) { message.setReferenceId(null); } else { message.setReferenceId(referenceId[0]); } message.setTitle(mail.getSubject()); Object content = mail.getContent(); if (content instanceof Multipart) { processMultipart((Multipart) content, message); } else if (content instanceof String) { processBody((String) content, mail.getContentType(), message); } event.addMessage(message); }
From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java
private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception { assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(), hasSize(1));// www . j av a2 s . c o m assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO)); MimeMessage[] messages = mail.getReceivedMessages(); assertThat(messages, arrayWithSize(1)); MimeMessage sentMessage = messages[0]; MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next(); assertThat(sentMessage.getFrom().length, is(1)); assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class)); InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0]; assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail())); assertThat(internetAddressFrom.getPersonal(), is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null))); assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1)); assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue()); assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue()); assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class)); InternetAddress internetAddressTo = (InternetAddress) sentMessage .getRecipients(Message.RecipientType.TO)[0]; assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail())); assertThat(internetAddressTo.getPersonal(), nullValue()); assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject())); if (verifiedMailToSend.getContent().getValue() instanceof Multipart) { assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass())); } else { assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""), is(verifiedMailToSend.getContent().getValue())); } assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date())); assertThat(sentMessage.getReplyTo().length, is(1)); if (verifiedMailToSend.isReplyToRequired()) { assertThat(sentMessage.getHeader("Reply-To"), notNullValue()); assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class)); InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0]; assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail())); assertThat(internetAddressReplyTo.getPersonal(), is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null))); } else { assertThat(sentMessage.getHeader("Reply-To"), nullValue()); assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString())); } }