List of usage examples for javax.mail Transport close
public synchronized void close() throws MessagingException
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments * // ww w.j av a2s. c o m * @param mailOptions * @return */ public boolean sendFiles(Map<String, Object> mailOptions) { logger.debug("IN"); try { final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory"; String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); File tempFolder = new File(tempFolderPath); if (!tempFolder.exists() || !tempFolder.isDirectory()) { logger.error("Temp Folder " + tempFolderPath + " does not exist or is not a directory: stop sending mail"); return false; } String smtphost = null; String pass = null; String smtpssl = null; String trustedStorePath = null; String user = null; String from = null; int smtpPort = 25; try { smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpportS == null) || smtpportS.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smtpPort = Integer.parseInt(smtpportS); } from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); } catch (Exception e) { logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e); throw new Exception( "Some E-mail configuration not set in table sbi_config: check you have all settings."); } String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null; Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP) : null; mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null; String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS) : null; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.p ort", Integer.toString(smtpPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null; Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("") ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT) : null; //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null; String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE) : null; String fileExtension = mailOptions.get(FILE_EXTENSION) != null ? (String) mailOptions.get(FILE_EXTENSION) : null; if (reportNameInSubject) { subject += " " + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt); // attach the file to the message boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT) : false; zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (isZipDocument) { logger.debug("Make zip"); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder); mp.addBodyPart(mbp2); } else { logger.debug("Attach single files"); SchedulerDataSource sds = null; MimeBodyPart bodyPart = null; try { String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { logger.debug("Attach file " + entries[i]); File f = new File(tempFolder + File.separator + entries[i]); byte[] content = getBytesFromFile(f); bodyPart = new MimeBodyPart(); sds = new SchedulerDataSource(content, contentType, entries[i]); //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension); bodyPart.setDataHandler(new DataHandler(sds)); bodyPart.setFileName(sds.getName()); mp.addBodyPart(bodyPart); } } catch (Exception e) { logger.error("Error while attaching files", e); } } // add the Multipart to the message msg.setContent(mp); logger.debug("Preparing to send mail"); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { logger.debug("Smtps mode active user " + user); //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smtpPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { logger.debug("Smtp mode"); //Use normal SMTP Transport.send(msg); } // logger.debug("delete tempFolder path "+tempFolder.getPath()); // boolean deleted = tempFolder.delete(); // logger.debug("Temp folder deleted "+deleted); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java
/** * This method performs the treatment of the technical send: * <ul>//from w w w. j av a2 s .co m * <li>connection to the SMTP server</li> * <li>sending</li> * <li>closing the connection</li> * </ul> * @param mail the original data from which the given {@link MimeMessage} has been initialized. * @param smtpConfiguration the SMTP configuration. * @param session the current mail session. * @param messageToSend the technical message to send. * @param batchedToAddresses the receivers of the message. * @throws MessagingException */ private void performSend(final MailToSend mail, final SmtpConfiguration smtpConfiguration, Session session, MimeMessage messageToSend, List<InternetAddress[]> batchedToAddresses) throws MessagingException { // Creating a Transport connection (TCP) final Transport transport; if (smtpConfiguration.isSecure()) { transport = session.getTransport(SmtpConfiguration.SECURE_TRANSPORT); } else { transport = session.getTransport(SmtpConfiguration.SIMPLE_TRANSPORT); } // Adding send reporting listener transport.addTransportListener(new SmtpMailSendReportListener(mail)); try { if (smtpConfiguration.isAuthenticate()) { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), smtpConfiguration.getUsername(), smtpConfiguration.getPassword()); } else { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), null, null); } for (InternetAddress[] toAddressBatch : batchedToAddresses) { messageToSend.setRecipients(mail.getTo().getRecipientType().getTechnicalType(), toAddressBatch); transport.sendMessage(messageToSend, toAddressBatch); } } finally { try { transport.close(); } catch (Exception e) { SilverTrace.error("mail", "SmtpMailSender.send()", "root.EX_IGNORED", "ClosingTransport", e); } } }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void rcptToError() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("550 error").recvLine() // QUIT .build().start(PORT);/*from w ww .j a v a2 s . c o m*/ Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.sendpartial", "true"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException e) { Assert.assertEquals(0, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(1, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void dataError() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("451 error").recvLine() // QUIT .build().start(PORT);/* w w w .j a v a 2s .c om*/ Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException e) { Assert.assertEquals(1, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(0, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void mailFromError() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("451 error").recvLine() // QUIT .build().start(PORT);/*from www. j a v a 2 s . c om*/ Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\n" + "Subject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException e) { Assert.assertEquals(0, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(0, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void dataException() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").build().start(PORT); Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))) { @Override/*from w w w.j a v a2 s . c om*/ public void writeTo(OutputStream os, String[] ignoreList) throws MessagingException { throw new MessagingException(); // exception while encoding } }; try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException expected) { } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java
/** * Actually send the given array of MimeMessages via JavaMail. * @param mimeMessages MimeMessage objects to send * @param originalMessages corresponding original message objects * that the MimeMessages have been created from (with same array * length and indices as the "mimeMessages" array), if any * @throws org.springframework.mail.MailAuthenticationException * in case of authentication failure/* w w w .j a va 2s .co m*/ * @throws org.springframework.mail.MailSendException * in case of failure when sending a message */ protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException { Map failedMessages = new HashMap(); try { Transport transport = getTransport(getSession()); transport.connect(getHost(), getPort(), getUsername(), getPassword()); try { for (int i = 0; i < mimeMessages.length; i++) { MimeMessage mimeMessage = mimeMessages[i]; try { if (mimeMessage.getSentDate() == null) { mimeMessage.setSentDate(new Date()); } mimeMessage.saveChanges(); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); } catch (MessagingException ex) { Object original = (originalMessages != null ? originalMessages[i] : mimeMessage); failedMessages.put(original, ex); } } } finally { transport.close(); } } catch (AuthenticationFailedException ex) { throw new MailAuthenticationException(ex); } catch (MessagingException ex) { throw new MailSendException("Mail server connection failed", ex); } if (!failedMessages.isEmpty()) { throw new MailSendException(failedMessages); } }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void sendPartially() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO 1 .sendLine("250 OK").recvLine() // RCPT TO 2 .sendLine("550 not found").recvLine() // RCPT TO 3 .sendLine("550 not found").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.sendpartial", "true"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\n" + "To: rcpt1@zimbra.com, rcpt2@zimbra.com, rcpt3@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try {/*from ww w.j a v a2s . com*/ transport.sendMessage(msg, msg.getAllRecipients()); } catch (SendFailedException e) { Assert.assertEquals(1, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(2, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt1@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt2@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt3@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendFiles(String to, String subject, String text, Collection<File> attachments) throws MessagingException { MimeMessage message = new MimeMessage(session); Transport t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);//from w w w. j a va 2 s .com message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); for (File attachment : attachments) { messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); t.close(); }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;//from w ww . jav a 2 s .c om } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }