List of usage examples for javax.mail Session getProperties
public Properties getProperties()
From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java
@Autowired public EmailManagerImpl(JavaMailSender mailSender, ServerConfigManager serverConfigManager, PlatformManager platformManager, ResourceManager resourceManager, Session mailSession, ConcurrentStatsCollector concurrentStatsCollector) { this.mailSender = mailSender; this.mailSession = mailSession; this.serverConfigManager = serverConfigManager; this.platformManager = platformManager; this.resourceManager = resourceManager; this.concurrentStatsCollector = concurrentStatsCollector; mailSmtpConnectiontimeout = Integer .parseInt(mailSession.getProperties().getProperty(HQConstants.MAIL_SMTP_CONNECTIONTIMEOUT)); mailSmtpTimeout = Integer.parseInt(mailSession.getProperties().getProperty(HQConstants.MAIL_SMTP_TIMEOUT)); mailSmtpHost = mailSession.getProperties().getProperty(HQConstants.MAIL_SMTP_HOST); }
From source file:org.masukomi.aspirin.core.RemoteDelivery.java
/** * We can assume that the recipients of this message are all going to the * same mail server. We will now rely on the JNDI to do DNS MX record lookup * and try to deliver to the multiple mail servers. If it fails, it should * throw an exception./*from w ww . j ava2 s . c o m*/ * * Creation date: (2/24/00 11:25:00 PM) * * @param mail * org.apache.james.core.MailImpl * @param session * javax.mail.Session * @return boolean Whether the delivery was successful and the message can * be deleted */ private boolean deliver(QuedItem qi, Session session) { MailAddress rcpt = null; try { if (log.isDebugEnabled()) { log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)"); } MailImpl mail = (MailImpl) qi.getMail(); MimeMessage message = mail.getMessage(); // Create an array of the recipients as InternetAddress objects Collection recipients = mail.getRecipients(); InternetAddress addr[] = new InternetAddress[recipients.size()]; int j = 0; // funky ass look because you can't getElementAt() in a Collection for (Iterator i = recipients.iterator(); i.hasNext(); j++) { MailAddress currentRcpt = (MailAddress) i.next(); addr[j] = currentRcpt.toInternetAddress(); } if (addr.length <= 0) { if (log.isDebugEnabled()) { log.debug("No recipients specified... returning"); } return true; } // Figure out which servers to try to send to. This collection // will hold all the possible target servers Collection targetServers = null; Iterator it = recipients.iterator(); while (it.hasNext()) { rcpt = (MailAddress) recipients.iterator().next(); if (!qi.recepientHasBeenHandled(rcpt)) { break; } } // theoretically it is possible to not hav eone that hasn't been // handled // however that's only if something has gone really wrong. if (rcpt != null) { String host = rcpt.getHost(); // Lookup the possible targets try { // targetServers = MXLookup.urlsForHost(host); // farking // unreliable jndi bs targetServers = getMXRecordsForHost(host); } catch (Exception e) { log.error(e); } if (targetServers == null || targetServers.size() == 0) { log.warn("No mail server found for: " + host); StringBuffer exceptionBuffer = new StringBuffer(128) .append("I found no MX record entries for the hostname ").append(host) .append(". I cannot determine where to send this message."); return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true); } else if (log.isTraceEnabled()) { log.trace(targetServers.size() + " servers found for " + host); } MessagingException lastError = null; Iterator i = targetServers.iterator(); while (i.hasNext()) { try { URLName outgoingMailServer = (URLName) i.next(); StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ") .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString()) .append(" to addresses ").append(Arrays.asList(addr)); if (log.isDebugEnabled()) { log.debug(logMessageBuffer.toString()); } ; // URLName urlname = new URLName("smtp://" // + outgoingMailServer); Properties props = session.getProperties(); if (mail.getSender() == null) { props.put("mail.smtp.from", "<>"); } else { String sender = mail.getSender().toString(); props.put("mail.smtp.from", sender); } // Many of these properties are only in later JavaMail // versions // "mail.smtp.ehlo" //default true // "mail.smtp.auth" //default false // "mail.smtp.dsn.ret" //default to nothing... appended // as // RET= after MAIL FROM line. // "mail.smtp.dsn.notify" //default to // nothing...appended as // NOTIFY= after RCPT TO line. Transport transport = null; try { transport = session.getTransport(outgoingMailServer); try { transport.connect(); } catch (MessagingException me) { log.error(me); // Any error on connect should cause the mailet // to // attempt // to connect to the next SMTP server associated // with this MX record, // assuming the number of retries hasn't been // exceeded. if (failMessage(qi, rcpt, me, false)) { return true; } else { continue; } } transport.sendMessage(message, addr); // log.debug("message sent to " +addr); /*TODO: catch failures that should result * in failure with no retries } catch (SendFailedException sfe){ qi.failForRecipient(que, ); */ } finally { if (transport != null) { transport.close(); transport = null; } } logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName()) .append(") sent successfully to ").append(outgoingMailServer); log.debug(logMessageBuffer.toString()); qi.succeededForRecipient(que, rcpt); return true; } catch (MessagingException me) { log.error(me); // MessagingException are horribly difficult to figure // out // what actually happened. StringBuffer exceptionBuffer = new StringBuffer(256) .append("Exception delivering message (").append(mail.getName()).append(") - ") .append(me.getMessage()); log.warn(exceptionBuffer.toString()); if ((me.getNextException() != null) && (me.getNextException() instanceof java.io.IOException)) { // This is more than likely a temporary failure // If it's an IO exception with no nested exception, // it's probably // some socket or weird I/O related problem. lastError = me; continue; } // This was not a connection or I/O error particular to // one // SMTP server of an MX set. Instead, it is almost // certainly // a protocol level error. In this case we assume that // this // is an error we'd encounter with any of the SMTP // servers // associated with this MX record, and we pass the // exception // to the code in the outer block that determines its // severity. throw me; } // end catch } // end while // If we encountered an exception while looping through, // throw the last MessagingException we caught. We only // do this if we were unable to send the message to any // server. If sending eventually succeeded, we exit // deliver() though the return at the end of the try // block. if (lastError != null) { throw lastError; } } // END if (rcpt != null) else { log.error("unable to find recipient that handn't already been handled"); } } catch (SendFailedException sfe) { log.error(sfe); boolean deleteMessage = false; Collection recipients = qi.getMail().getRecipients(); // Would like to log all the types of email addresses if (log.isDebugEnabled()) { log.debug("Recipients: " + recipients); } /* * The rest of the recipients failed for one reason or another. * * SendFailedException actually handles this for us. For example, if * you send a message that has multiple invalid addresses, you'll * get a top-level SendFailedException that that has the valid, * valid-unsent, and invalid address lists, with all of the server * response messages will be contained within the nested exceptions. * [Note: the content of the nested exceptions is implementation * dependent.] * * sfe.getInvalidAddresses() should be considered permanent. * sfe.getValidUnsentAddresses() should be considered temporary. * * JavaMail v1.3 properly populates those collections based upon the * 4xx and 5xx response codes. * */ if (sfe.getInvalidAddresses() != null) { Address[] address = sfe.getInvalidAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse invalid address: " + pe.getMessage()); } } } if (log.isDebugEnabled()) { log.debug("Invalid recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, true); } } if (sfe.getValidUnsentAddresses() != null) { Address[] address = sfe.getValidUnsentAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse unsent address: " + pe.getMessage()); } pe.printStackTrace(); } } if (log.isDebugEnabled()) { log.debug("Unsent recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, false); } } return deleteMessage; } catch (MessagingException ex) { log.error(ex); // We should do a better job checking this... if the failure is a // general // connect exception, this is less descriptive than more specific // SMTP command // failure... have to lookup and see what are the various Exception // possibilities // Unable to deliver message after numerous tries... fail // accordingly // We check whether this is a 5xx error message, which // indicates a permanent failure (like account doesn't exist // or mailbox is full or domain is setup wrong). // We fail permanently if this was a 5xx error return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0))); } catch (Throwable t) { log.error(t); } /* * 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 we get a MessagingException on each transport.connect(), * e.g., if there is only one server and we get a connect exception. * Return FALSE to keep run() from deleting the message. */ return false; }
From source file:org.oscarehr.oscar_apps.util.Log4JGmailExecutorTask.java
private void sendEmail() throws EmailException { HtmlEmail email = new HtmlEmail(); email.setHostName(smtpServer);//from w w w . java2s . co m if (smtpUser != null && smtpPassword != null) email.setAuthentication(smtpUser, smtpPassword); if (smtpSslPort != null) { email.setSSL(true); email.setSslSmtpPort(smtpSslPort); } Session session = email.getMailSession(); Properties properties = session.getProperties(); properties.setProperty("mail.smtp.connectiontimeout", "20000"); properties.setProperty("mail.smtp.timeout", "20000"); email.addTo(recipientEmailAddress, recipientEmailAddress); email.setFrom(smtpUser, smtpUser); email.setSubject(subject); email.setHtmlMsg(contents); email.setTextMsg(contents); email.send(); }
From source file:org.oscarehr.util.EmailUtils.java
/** * This method will return an HtmlEmail object populated with * the values passed in, ignoring the parameters in the configuration file. */// ww w . j a va 2s . c om public static HtmlEmail getHtmlEmail(String smtpServer, String smtpPort, String smtpUser, String smtpPassword, String connectionSecurity) throws EmailException { logger.debug("smtpServer=" + smtpServer + ", smtpSslPort=" + smtpPort + ", smtpUser=" + smtpUser + ", smtpPassword=" + smtpPassword + ",connectionSecurity=" + connectionSecurity); HtmlEmail email = null; if (RECIPIENT_OVERRIDE_KEY != null || printInsteadOfSend) email = new HtmlEmailWrapper(); else email = new HtmlEmail(); email.setHostName(smtpServer); if (smtpUser != null && smtpPassword != null) email.setAuthentication(smtpUser, smtpPassword); Session session = email.getMailSession(); if (connectionSecurity != null) { if (connectionSecurity.equals(CONNECTION_SECURITY_STARTTLS)) { session.getProperties().setProperty(Email.MAIL_TRANSPORT_TLS, "true"); email.setTLS(true); } else if (connectionSecurity.equals(CONNECTION_SECURITY_SSL)) { email.setSSL(true); } } if (smtpPort != null) { email.setSslSmtpPort(smtpPort); } Properties properties = session.getProperties(); properties.setProperty("mail.smtp.connectiontimeout", "20000"); properties.setProperty("mail.smtp.timeout", "20000"); return (email); }
From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java
/** * Apply server configuration to email./* ww w.j a v a2s . c o m*/ */ @VisibleForTesting Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException { mail.setHostName(configuration.getHost()); mail.setSmtpPort(configuration.getPort()); mail.setAuthentication(configuration.getUsername(), configuration.getPassword()); mail.setStartTLSEnabled(configuration.isStartTlsEnabled()); mail.setStartTLSRequired(configuration.isStartTlsRequired()); mail.setSSLOnConnect(configuration.isSslOnConnectEnabled()); mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled()); mail.setSslSmtpPort(Integer.toString(configuration.getPort())); // default from address if (mail.getFromAddress() == null) { mail.setFrom(configuration.getFromAddress()); } // apply subject prefix if configured String subjectPrefix = configuration.getSubjectPrefix(); if (subjectPrefix != null) { String subject = mail.getSubject(); mail.setSubject(String.format("%s %s", subjectPrefix, subject)); } // do this last (mail properties are set up from the email fields when you get the mail session) if (configuration.isNexusTrustStoreEnabled()) { SSLContext context = trustStore.getSSLContext(); Session session = mail.getMailSession(); Properties properties = session.getProperties(); properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS); properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true); properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory()); } return mail; }
From source file:org.sourceforge.net.javamail4ews.util.Util.java
public static Configuration getConfiguration(Session pSession) { try {//from w w w. j ava 2s . c o m PropertiesConfiguration prop = new PropertiesConfiguration(); for (Object aKey : pSession.getProperties().keySet()) { Object aValue = pSession.getProperties().get(aKey); prop.addProperty(aKey.toString(), aValue); } CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(prop); URL lURL = Thread.currentThread().getContextClassLoader() .getResource("javamail-ews-bridge.default.properties"); config.addConfiguration(new PropertiesConfiguration(lURL)); return config; } catch (ConfigurationException e) { throw new RuntimeException(e.getMessage(), e); } }