List of usage examples for javax.mail Transport connect
public void connect() throws MessagingException
From source file:org.gcaldaemon.core.GmailEntry.java
private final void connectSMTP(String username, String password) throws Exception { // Create SMTP session Properties props = (Properties) System.getProperties().clone(); props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.user", username); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); // Connect to Gmail via SMTP+TLS GmailAuthenticator login = new GmailAuthenticator(username, password); smtpSession = Session.getDefaultInstance(props, login); Transport smtpTransport = smtpSession.getTransport("smtp"); smtpTransport.connect(); log.debug("Gmail's SMTP service has been connected successfully."); }
From source file:com.gcrm.util.mail.MailService.java
public void sendSimpleMail(String toAddress) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;//from www .j a v a 2 s . com if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } Session mailSession = this.createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(emailSetting.getFrom_address()); helper.setTo(toAddress); helper.setSubject("Test Mail From " + emailSetting.getFrom_name()); helper.setText("This is test mail from " + emailSetting.getFrom_name(), true); transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java
private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content) throws ConfigurationException { try {/* w w w .j a v a2 s. c o m*/ log.debug("Sending mail."); MiscUtil.assertNotNull(subject, "subject"); MiscUtil.assertNotNull(recipient, "recipient"); MiscUtil.assertNotNull(content, "content"); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", config.getSMTPMailHost()); log.trace("Mail host: " + config.getSMTPMailHost()); if (config.getSMTPMailPort() != null) { log.trace("Mail port: " + config.getSMTPMailPort()); props.setProperty("mail.port", config.getSMTPMailPort()); } if (config.getSMTPMailUsername() != null) { log.trace("Mail user: " + config.getSMTPMailUsername()); props.setProperty("mail.user", config.getSMTPMailUsername()); } if (config.getSMTPMailPassword() != null) { log.trace("Mail password: " + config.getSMTPMailPassword()); props.setProperty("mail.password", config.getSMTPMailPassword()); } Session mailSession = Session.getDefaultInstance(props, null); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject); log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress()); message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName())); log.trace("Recipient: " + recipient); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); log.trace("Creating multipart content of mail."); MimeMultipart multipart = new MimeMultipart("related"); log.trace("Adding first part (html)"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15"); multipart.addBodyPart(messageBodyPart); // log.trace("Adding mail images"); // messageBodyPart = new MimeBodyPart(); // for (Image image : images) { // messageBodyPart.setDataHandler(new DataHandler(image)); // messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">"); // multipart.addBodyPart(messageBodyPart); // } message.setContent(multipart); transport.connect(); log.trace("Sending mail message."); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); log.trace("Successfully sent."); transport.close(); } catch (MessagingException e) { throw new ConfigurationException(e); } catch (UnsupportedEncodingException e) { throw new ConfigurationException(e); } }
From source file:com.basicservice.service.MailService.java
public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception { try {/* w ww. j a va 2 s.co m*/ Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", 587); props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(); Session mailSession = Session.getDefaultInstance(props, auth); // mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); Multipart multipart = new MimeMultipart("alternative"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); message.setFrom(new InternetAddress(from)); message.setSubject(subject, "UTF-8"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } catch (Exception e) { LOG.debug("Exception while sending email: ", e); throw e; } }
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.// w w w . j ava 2s . 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:com.gcrm.util.mail.MailService.java
public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames, File[] files) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;//from ww w .j ava 2 s.c om if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } if (from == null) { from = emailSetting.getFrom_address(); } Session mailSession = createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); if (fileNames != null && files != null) { String fileName = null; File file = null; for (int i = 0; i < fileNames.length; i++) { fileName = fileNames[i]; file = files[i]; if (fileName != null && file != null) { helper.addAttachment(fileName, file); } } } transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @throws MessagingException/* w w w . j av a 2 s . c om*/ * @throws IOException */ public void send() throws MessagingException, IOException { buildBodyContent(); this.message.setHeader("X-Mailer", CubusConstants.APPLICATION_NAME); this.message.setSentDate(new Date()); Transport transport = this.session.getTransport(); if (!transport.isConnected()) { transport.connect(); } transport.sendMessage(this.message, this.message.getAllRecipients()); transport.close(); }
From source file:com.youxifan.utils.EMail.java
/** * Send Mail direct/*from w ww. j a va 2 s . c o m*/ * @return OK or error message */ public String send() { log.info("(" + m_smtpHost + ") " + m_from + " -> " + m_to); m_sentMsg = null; // if (!isValid(true)) { m_sentMsg = "Invalid Data"; return m_sentMsg; } // Properties props = System.getProperties(); props.put("mail.store.protocol", "smtp"); props.put("mail.transport.protocol", "smtp"); props.put("mail.host", m_smtpHost); // Bit-Florin David props.put("mail.smtp.port", String.valueOf(m_smtpPort)); // TLS settings if (m_isSmtpTLS) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.port", String.valueOf(m_smtpPort)); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); } // Session session = null; try { if (m_auth != null) // createAuthenticator was called props.put("mail.smtp.auth", "true"); // if (m_smtpHost.equalsIgnoreCase("smtp.gmail.com")) { // // TODO: make it configurable // // Enable gmail port and ttls - Hardcoded // props.put("mail.smtp.port", "587"); // props.put("mail.smtp.starttls.enable", "true"); // } session = Session.getInstance(props, m_auth); } catch (SecurityException se) { log.warn("Auth=" + m_auth + " - " + se.toString()); m_sentMsg = se.toString(); return se.toString(); } catch (Exception e) { log.warn("Auth=" + m_auth, e); m_sentMsg = e.toString(); return e.toString(); } try { // m_msg = new MimeMessage(session); m_msg = new SMTPMessage(session); // Addresses m_msg.setFrom(m_from); InternetAddress[] rec = getTos(); if (rec.length == 1) m_msg.setRecipient(Message.RecipientType.TO, rec[0]); else m_msg.setRecipients(Message.RecipientType.TO, rec); rec = getCcs(); if (rec != null && rec.length > 0) m_msg.setRecipients(Message.RecipientType.CC, rec); rec = getBccs(); if (rec != null && rec.length > 0) m_msg.setRecipients(Message.RecipientType.BCC, rec); if (m_replyTo != null) m_msg.setReplyTo(new Address[] { m_replyTo }); // m_msg.setSentDate(new java.util.Date()); m_msg.setHeader("Comments", "Becit Mail"); m_msg.setHeader("Comments", "Becit ERP Mail"); // m_msg.setDescription("Description"); // SMTP specifics m_msg.setAllow8bitMIME(true); // Send notification on Failure & Success - no way to set envid in Java yet // m_msg.setNotifyOptions (SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS); // Bounce only header m_msg.setReturnOption(SMTPMessage.RETURN_HDRS); // m_msg.setHeader("X-Mailer", "msgsend"); // setContent(); m_msg.saveChanges(); // log.fine("message =" + m_msg); // // Transport.send(msg); Transport t = session.getTransport("smtp"); // log.fine("transport=" + t); t.connect(); // t.connect(m_smtpHost, user, password); // log.fine("transport connected"); Transport.send(m_msg); // t.sendMessage(msg, msg.getAllRecipients()); log.info("Success - MessageID=" + m_msg.getMessageID()); } catch (MessagingException me) { Exception ex = me; StringBuffer sb = new StringBuffer("(ME)"); boolean printed = false; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (!printed) { if (invalid != null && invalid.length > 0) { sb.append(" - Invalid:"); for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null && validUnsent.length > 0) { sb.append(" - ValidUnsent:"); for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null && validSent.length > 0) { sb.append(" - ValidSent:"); for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]); } printed = true; } if (sfex.getNextException() == null) sb.append(" ").append(sfex.getLocalizedMessage()); } else if (ex instanceof AuthenticationFailedException) { sb.append(" - Invalid Username/Password - " + m_auth); } else // other MessagingException { String msg = ex.getLocalizedMessage(); if (msg == null) sb.append(": ").append(ex.toString()); else { if (msg.indexOf("Could not connect to SMTP host:") != -1) { int index = msg.indexOf('\n'); if (index != -1) msg = msg.substring(0, index); String cc = "??"; msg += " - AD_Client_ID=" + cc; } String className = ex.getClass().getName(); if (className.indexOf("MessagingException") != -1) sb.append(": ").append(msg); else sb.append(" ").append(className).append(": ").append(msg); } } // Next Exception if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); // error loop m_sentMsg = sb.toString(); return sb.toString(); } catch (Exception e) { log.warn("", e); m_sentMsg = e.getLocalizedMessage(); return e.getLocalizedMessage(); } // m_sentMsg = SENT_OK; return m_sentMsg; }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Send a Collection of Mails (multiple emails) * // w ww.j a v a 2s.c o m * @param emails Mail Collection * @return True in any case (TODO ?) */ public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context) throws MessagingException, UnsupportedEncodingException { Session session = null; Transport transport = null; int emailCount = emails.size(); int count = 0; int sendFailedCount = 0; try { for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext();) { count++; Mail mail = emailIt.next(); LOGGER.info("Sending email: " + mail.toString()); if ((transport == null) || (session == null)) { // initialize JavaMail Session and Transport Properties props = initProperties(mailConfiguration); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (!mailConfiguration.usesAuthentication()) { // no auth info - typical 127.0.0.1 open relay scenario transport.connect(); } else { // auth info present - typical with external smtp server transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword()); } } try { MimeMessage message = createMimeMessage(mail, session, context); if (message == null) { continue; } transport.sendMessage(message, message.getAllRecipients()); // close the connection every other 100 emails if ((count % 100) == 0) { try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { LOGGER.error("MessagingException has occured.", ex); } transport = null; session = null; } } catch (SendFailedException ex) { sendFailedCount++; LOGGER.error("SendFailedException has occured.", ex); LOGGER.error("Detailed email information" + mail.toString()); if (emailCount == 1) { throw ex; } if ((emailCount != 1) && (sendFailedCount > 10)) { throw ex; } } catch (MessagingException mex) { LOGGER.error("MessagingException has occured.", mex); LOGGER.error("Detailed email information" + mail.toString()); if (emailCount == 1) { throw mex; } } catch (XWikiException e) { LOGGER.error("XWikiException has occured.", e); } catch (IOException e) { LOGGER.error("IOException has occured.", e); } } } finally { try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { LOGGER.error("MessagingException has occured.", ex); } LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count); } return true; }
From source file:org.libreplan.web.common.ConfigurationController.java
/** * Test E-mail connection./*from ww w . j a v a 2 s . co m*/ * * @param host * the host * @param port * the port * @param username * the username * @param password * the password */ private void testEmailConnection(String host, String port, String username, String password) { Properties props = System.getProperties(); Transport transport = null; try { if ("SMTP".equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtp.port", port); props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if ("".equals(username) && "".equals(password)) { transport.connect(); } } else if (STARTTLS_PROTOCOL.equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtps.port", port); props.setProperty("mail.smtps.host", host); props.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtps"); if (!"".equals(username) && password != null) { transport.connect(host, username, password); } } messages.clearMessages(); if (transport != null) { if (transport.isConnected()) { messages.showMessage(Level.INFO, _("Connection successful!")); } else if (!transport.isConnected()) { messages.showMessage(Level.WARNING, _("Connection unsuccessful")); } } } catch (AuthenticationFailedException e) { messages.clearMessages(); messages.showMessage(Level.ERROR, _("Invalid credentials")); } catch (MessagingException e) { LOG.error(e); messages.clearMessages(); messages.showMessage(Level.ERROR, _("Cannot connect")); } catch (Exception e) { LOG.error(e); messages.clearMessages(); messages.showMessage(Level.ERROR, _("Failed to connect")); } }