List of usage examples for javax.mail MessagingException MessagingException
public MessagingException(String s)
From source file:de.saly.elasticsearch.support.IndexableMailMessage.java
private static String getText(final Part p, int depth) throws MessagingException, IOException { if (depth >= 100) { throw new IOException("Endless recursion detected "); }/*from w w w . ja v a2s. c o m*/ // TODO fix encoding for buggy encoding headers if (p.isMimeType("text/*")) { Object content = null; try { content = p.getContent(); } catch (final Exception e) { logger.error("Unable to index the content of a message due to {}", e.toString()); return null; } if (content instanceof String) { final String s = (String) p.getContent(); return s; } if (content instanceof InputStream) { final InputStream in = (InputStream) content; // TODO guess encoding with // http://code.google.com/p/juniversalchardet/ final String s = IOUtils.toString(in, "UTF-8"); IOUtils.closeQuietly(in); return s; } throw new MessagingException("Unknown content class representation: " + content.getClass()); } if (p.isMimeType("multipart/alternative")) { // prefer plain text over html text final Multipart mp = (Multipart) p.getContent(); String text = null; for (int i = 0; i < mp.getCount(); i++) { final Part bp = mp.getBodyPart(i); if (bp.isMimeType("text/html")) { if (text == null) { text = getText(bp, ++depth); } continue; } else if (bp.isMimeType("text/plain")) { final String s = getText(bp, ++depth); if (s != null) { return s; } } else { return getText(bp, ++depth); } } return text; } else if (p.isMimeType("multipart/*")) { final Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { final String s = getText(mp.getBodyPart(i), ++depth); if (s != null) { return s; } } } return null; }
From source file:com.hs.mail.mailet.RemoteDelivery.java
/** * We arranged that the recipients are all going to the same mail server. We * will now rely on the DNS server to do DNS MX record lookup and try to * deliver to the multiple mail servers. If it fails, we should decide that * the failure is permanent or temporary. * /*from w ww .j a v a 2 s . c o m*/ * @param host * the same host of recipients * @param recipients * recipients who are all going to the same mail server * @param message * Mail object to be delivered * @param mimemsg * MIME message representation of the message * @return true if the delivery was successful or permanent failure so the * message should be deleted, otherwise false and the message will * be tried to send again later */ private boolean deliver(String host, Collection<Recipient> recipients, SmtpMessage message, MimeMessage mimemsg) { // Prepare javamail recipients InternetAddress[] addresses = new InternetAddress[recipients.size()]; Iterator<Recipient> it = recipients.iterator(); for (int i = 0; it.hasNext(); i++) { Recipient rcpt = it.next(); addresses[i] = rcpt.toInternetAddress(); } try { // Lookup the possible targets Iterator<HostAddress> targetServers = null; if (null == gateway) { targetServers = getSmtpHostAddresses(host); } else { targetServers = getGatewaySmtpHostAddresses(gateway); } if (!targetServers.hasNext()) { logger.info("No mail server found for: " + host); StringBuilder exceptionBuffer = new StringBuilder(128) .append("There are no DNS entries for the hostname ").append(host) .append(". I cannot determine where to send this message."); return failMessage(message, addresses, new MessagingException(exceptionBuffer.toString()), false); } Properties props = session.getProperties(); if (message.isNotificationMessage()) { props.put("mail.smtp.from", "<>"); } else { props.put("mail.smtp.from", message.getFrom().getMailbox()); } MessagingException lastError = null; StringBuilder logBuffer = null; HostAddress outgoingMailServer = null; while (targetServers.hasNext()) { try { outgoingMailServer = targetServers.next(); logBuffer = new StringBuilder(256).append("Attempting to deliver message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(addresses)); logger.info(logBuffer.toString()); Transport transport = null; try { transport = session.getTransport(outgoingMailServer); try { if (authUser != null) { transport.connect(outgoingMailServer.getHostName(), authUser, authPass); } else { transport.connect(); } } catch (MessagingException e) { // Any error on connect should cause the mailet to // attempt to connect to the next SMTP server // associated with this MX record. logger.error(e.getMessage()); continue; } transport.sendMessage(mimemsg, addresses); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { } transport = null; } } logBuffer = new StringBuilder(256).append("Successfully sent message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(addresses)); logger.info(logBuffer.toString()); recipients.clear(); return true; } catch (SendFailedException sfe) { if (sfe.getValidSentAddresses() != null) { Address[] validSent = sfe.getValidSentAddresses(); if (validSent.length > 0) { logBuffer = new StringBuilder(256).append("Successfully sent message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(validSent)); logger.info(logBuffer.toString()); // Remove the addresses to which this message was // sent successfully List<InternetAddress> temp = new ArrayList<InternetAddress>(); for (int i = 0; i < addresses.length; i++) { if (!ArrayUtils.contains(validSent, addresses[i])) { if (addresses[i] != null) { temp.add(addresses[i]); } } } addresses = temp.toArray(new InternetAddress[temp.size()]); removeAll(recipients, validSent); } } if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; // If permanent error 5xx, terminate this delivery // attempt by re-throwing the exception if (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599) throw sfe; } if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) { // Valid addresses remained, so continue with any other server. if (logger.isDebugEnabled()) logger.debug("Send failed, " + sfe.getValidUnsentAddresses().length + " valid recipients(" + Arrays.asList(sfe.getValidUnsentAddresses()) + ") remain, continuing with any other servers"); lastError = sfe; continue; } else { // There are no valid addresses left to send, so re-throw throw sfe; } } catch (MessagingException me) { Exception ne; if ((ne = me.getNextException()) != null && ne instanceof IOException) { // It can be some socket or weird I/O related problem. lastError = me; continue; } throw me; } } // end while if (lastError != null) { throw lastError; } } catch (SendFailedException sfe) { boolean deleteMessage = false; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599); } else { // Sometimes we'll get a normal SendFailedException with nested // SMTPAddressFailedException, so use the latter RetCode MessagingException me = sfe; Exception ne; while ((ne = me.getNextException()) != null && ne instanceof MessagingException) { me = (MessagingException) ne; if (me instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) me; deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599); } } } if (!ArrayUtils.isEmpty(sfe.getInvalidAddresses())) { // Invalid addresses should be considered permanent Address[] invalid = sfe.getInvalidAddresses(); removeAll(recipients, invalid); deleteMessage = failMessage(message, invalid, sfe, true); } if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) { // Vaild-unsent addresses should be considered temporary deleteMessage = failMessage(message, sfe.getValidUnsentAddresses(), sfe, false); } return deleteMessage; } catch (MessagingException mex) { // Check whether this is a permanent error (like account doesn't // exist or mailbox is full or domain is setup wrong) // We fail permanently if this was 5xx error. return failMessage(message, addresses, mex, ('5' == mex.getMessage().charAt(0))); } // If we get here, we've exhausted the loop of servers without sending // the message or throwing an exception. // One case where this might happen is if there is no server we can // connect. So this should be considered temporary return failMessage(message, addresses, new MessagingException("No mail server(s) available at this time."), false); }
From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java
private static String getText(final Part p, int depth, final boolean preferHtmlContent) throws MessagingException, IOException { if (depth >= 100) { throw new IOException("Endless recursion detected "); }/*from ww w. j ava 2 s . com*/ // TODO fix encoding for buggy encoding headers if (p.isMimeType("text/*")) { Object content = null; try { content = p.getContent(); } catch (final Exception e) { logger.error("Unable to index the content of a message due to {}", e.toString()); return null; } if (content instanceof String) { final String s = (String) p.getContent(); return s; } if (content instanceof InputStream) { final InputStream in = (InputStream) content; // TODO guess encoding with // http://code.google.com/p/juniversalchardet/ final String s = IOUtils.toString(in, "UTF-8"); IOUtils.closeQuietly(in); return s; } throw new MessagingException("Unknown content class representation: " + content.getClass()); } if (p.isMimeType("multipart/alternative")) { // prefer plain text over html text final Multipart mp = (Multipart) p.getContent(); String text = null; for (int i = 0; i < mp.getCount(); i++) { final Part bp = mp.getBodyPart(i); if (bp.isMimeType("text/html")) { if (text == null) { text = getText(bp, ++depth, preferHtmlContent); } if (preferHtmlContent) { return text; } else { continue; } } else if (bp.isMimeType("text/plain")) { final String s = getText(bp, ++depth, preferHtmlContent); if (s != null && !preferHtmlContent) { return s; } else { continue; } } else { return getText(bp, ++depth, preferHtmlContent); } } return text; } else if (p.isMimeType("multipart/*")) { final Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { final String s = getText(mp.getBodyPart(i), ++depth, preferHtmlContent); if (s != null) { return s; } } } return null; }
From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java
/** * ??// ww w .j av a 2s . co m * * @param config javelin.properties??? * @param entry ?? * @return ??? * @throws MessagingException ?????? */ protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry) throws MessagingException { // JavaMail??? Properties props = System.getProperties(); String smtpServer = this.config_.getSmtpServer(); if (smtpServer == null || smtpServer.length() == 0) { LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED); String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified"; String messageDetail = CommunicatorMessages.getMessage(detailMessageKey); throw new MessagingException(messageDetail); } props.setProperty(SMTP_HOST_KEY, smtpServer); int smtpPort = config.getSmtpPort(); props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort)); // ??????? Session session = null; if (authenticator_ == null) { // ????? session = Session.getDefaultInstance(props); } else { // ??? props.setProperty(SMTP_AUTH_KEY, "true"); session = Session.getDefaultInstance(props, authenticator_); } // MIME?? MimeMessage message = new MimeMessage(session); // ?? // : Date date = new Date(); String encoding = this.config_.getSmtpEncoding(); message.setHeader("X-Mailer", X_MAILER); message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\""); message.setSentDate(date); // :from String from = this.config_.getSmtpFrom(); InternetAddress fromAddr = new InternetAddress(from); message.setFrom(fromAddr); // :to String[] recipients = this.config_.getSmtpTo().split(","); for (String toStr : recipients) { InternetAddress toAddr = new InternetAddress(toStr); message.addRecipient(Message.RecipientType.TO, toAddr); } // :body, subject String subject; String body; subject = createSubject(entry, date); try { body = createBody(entry, date); } catch (IOException ex) { LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, ""); body = createDefaultBody(entry, date); } message.setSubject(subject, encoding); message.setText(body, encoding); return message; }
From source file:mitm.application.djigzo.james.mailets.Relay.java
private void initRelayProcessor() throws MessagingException { relayProcessor = getInitParameter(Parameter.RELAY_PROCESSOR.name); if (StringUtils.isBlank(relayProcessor)) { throw new MessagingException("relayProcessor must be specified."); }/*from w ww.j a v a 2 s. co m*/ }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Create a reply message to the given message. The reply message is * addressed to only the from / reply address or all receipients based on * the replyToAll flag.// w w w . ja v a 2s. c o m * * @param fromName DOCUMENT ME! * @param fromEmail DOCUMENT ME! * @param message The message which to reply * @param body The attached text to include in the reply * @param replyToAll Reply to all receipients of the original message * * @return Message Reply message * * @exception MessagingException if the message contents are invalid */ public static Message createReply(Address[] from, Message message, boolean replyToAll) throws MessagingException { if ((from == null) || (from.length <= 0)) { throw new MessagingException("The from is null"); } // create an empty reply message Message xreply = message.reply(replyToAll); // set the default from address xreply.setFrom(from[0]); // Message.reply() may set the "replied to" flag, so // attempt to save that new state and fail silently... try { message.saveChanges(); } catch (MessagingException ex) { } return xreply; }
From source file:de.xirp.mail.MailManager.java
/** * Checks the given {@link de.xirp.mail.Mail}, if * the minimum requirements are met for sending the mail. * /*w ww.ja v a 2s . c o m*/ * @param mail * The mail to check. * @throws MessagingException * if something is wrong with the mail. * @see de.xirp.mail.Mail */ private static void checkMail(Mail mail) throws MessagingException { if (mail.getTo().size() <= 0) { throw new MessagingException(I18n.getString("MailManager.exception.noReceiver") //$NON-NLS-1$ + Constants.LINE_SEPARATOR); } }
From source file:mitm.application.djigzo.james.mailets.Relay.java
private void initBounceProcessor() throws MessagingException { bounceProcessor = getInitParameter(Parameter.BOUNCE_PROCESSOR.name); if (StringUtils.isBlank(bounceProcessor)) { throw new MessagingException("bounceProcessor must be specified."); }/*from ww w . j a va 2s . c o m*/ }
From source file:mitm.common.mail.BodyPartUtils.java
/** * Extracts the message from the RFC822 attachment. * @throws MessagingException /*from www. java2 s .c om*/ * @throws IOException */ public static MimeMessage extractFromRFC822(Part rfc822) throws IOException, MessagingException { if (!rfc822.isMimeType("message/rfc822")) { throw new MessagingException("Part is-not-a message/rfc822 but " + rfc822.getContentType()); } return new MimeMessage(MailSession.getDefaultSession(), rfc822.getInputStream()); }
From source file:fi.foyt.fni.view.gamelibrary.GameLibraryProposeGameBackingBean.java
private void sendNotifications(BookPublication publication) throws MessagingException { boolean success = false; List<User> librarians = permissionController .listUsersByPermission(Permission.GAMELIBRARY_MANAGE_PUBLICATIONS); for (User librarian : librarians) { if (sendNotificationEmail(librarian, publication)) { success = true;//from w w w .j a v a2 s . c o m } } if (!success) { throw new MessagingException("Could not send notification mail"); } }