List of usage examples for javax.mail Transport close
public synchronized void close() throws MessagingException
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/*from ww w . ja v a2 s . co m*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;/*from ww w .ja va 2s . com*/ props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.opencastproject.kernel.mail.BaseSmtpService.java
/** * Sends <code>message</code> using the configured transport. * * @param message// ww w.j av a 2s . co m * the message * @throws MessagingException * if sending the message failed */ public void send(MimeMessage message) throws MessagingException { if (!productionMode) { logger.debug("Skipping sending of message {} due to test mode", message); return; } Transport t = getSession().getTransport(mailTransport); try { if (user != null) t.connect(user, password); else t.connect(); t.sendMessage(message, message.getAllRecipients()); } finally { t.close(); } }
From source file:org.opencastproject.kernel.mail.SmtpService.java
/** * Sends <code>message</code> using the configured transport. * /*from ww w. j ava 2 s .co m*/ * @param message * the message * @throws MessagingException * if sending the message failed */ public void send(MimeMessage message) throws MessagingException { Transport t = getSession().getTransport(mailTransport); try { if (mailUser != null) t.connect(mailUser, mailPassword); else t.connect(); t.sendMessage(message, message.getAllRecipients()); } finally { t.close(); } }
From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java
/** * @param mimeMessage//from w w w. j ava 2 s. c o m * @throws MessagingException */ private void _send(MimeMessage mimeMessage) throws MessagingException { Transport transport = null; try { transport = session.getTransport(); transport.connect(); mimeMessage.setSentDate(new Date()); mimeMessage.saveChanges(); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); } finally { if (transport != null && transport.isConnected()) { transport.close(); } } }
From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java
/** * Sends <code>message</code> using the configured transport. * //from w w w. j ava 2s. c om * @param message * the message * @throws MessagingException * if sending the message failed */ public void send(MimeMessage message) throws MessagingException { Transport t = getSession().getTransport(MAIL_TRANSPORT); try { if (mailUser != null) t.connect(mailUser, mailPassword); else t.connect(); t.sendMessage(message, message.getAllRecipients()); } finally { t.close(); } }
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {/*from w ww .j av a2 s .c om*/ // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message// w w w . ja v a 2 s . c o m * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }// w w w. j a v a 2s . c o m Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;//from www.j a va2s . c om String fileExtension; String nameSuffix; JobExecutionContext jobExecutionContext; logger.debug("IN"); try { contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); nameSuffix = dispatchContext.getNameSuffix(); jobExecutionContext = dispatchContext.getJobExecutionContext(); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; int smptPort = 25; if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); /* if( (user==null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); if( (pass==null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); */ String mailTos = ""; List dlIds = dispatchContext.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(document, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); Session session = null; if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); logger.debug("Connecting to mail server without authentication"); } else { props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(user, pass); //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(smptPort)); 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.getInstance(props, auth); logger.debug("Connecting to mail server with authentication"); } // 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 IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = document.getName() + nameSuffix; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType, document.getName() + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); //mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } if (jobExecutionContext.getNextFireTime() == null) { String triggername = jobExecutionContext.getTrigger().getName(); dlIds = dispatchContext.getDlIds(); it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl, (document.getId()).intValue(), triggername); } } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }