List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;//w w w.j a v a 2s . com String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); 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); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String 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"); String 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"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // 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(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.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; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + 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); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.tremolosecurity.proxy.auth.PasswordReset.java
private void sendEmail(SmtpMessage msg) throws MessagingException { Properties props = new Properties(); props.setProperty("mail.smtp.host", this.reset.getSmtpServer()); props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort())); props.setProperty("mail.smtp.user", reset.getSmtpUser()); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS())); //props.setProperty("mail.debug", "true"); //props.setProperty("mail.socket.debug", "true"); if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) { props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost()); }/*from w ww . j a va2 s. c o m*/ if (reset.isUseSocks()) { props.setProperty("mail.smtp.socks.host", reset.getSocksHost()); props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort())); props.setProperty("mail.smtps.socks.host", reset.getSocksHost()); props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort())); } //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword)); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword()); } }); //Session session = Session.getInstance(props, null); session.setDebugOut(System.out); //session.setDebug(true); //Transport tr = session.getTransport("smtp"); //tr.connect(); //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword); Message msgToSend = new MimeMessage(session); msgToSend.setFrom(new InternetAddress(msg.from)); msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to)); msgToSend.setSubject(msg.subject); msgToSend.setText(msg.msg); msgToSend.saveChanges(); Transport.send(msgToSend); //tr.sendMessage(msg, msg.getAllRecipients()); //tr.close(); }
From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????//w w w . ja v a 2 s . c o m * @param toAddressStr * ?To * @param ccAddressStr * ?Cc * @param subject * ?? * @param content * * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ?? return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc, String subject, String body, List<MailFile> mailFiles) throws MessagingException, UnsupportedEncodingException { Message jxMessage = new MimeMessage(_imapConnection.getSession()); jxMessage.setFrom(new InternetAddress(sender, personalName)); jxMessage.addRecipients(Message.RecipientType.TO, to); jxMessage.addRecipients(Message.RecipientType.CC, cc); jxMessage.addRecipients(Message.RecipientType.BCC, bcc); jxMessage.setSentDate(new Date()); jxMessage.setSubject(subject);/*from w w w. ja v a2s . c om*/ MimeMultipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8); multipart.addBodyPart(messageBodyPart); if (mailFiles != null) { for (MailFile mailFile : mailFiles) { File file = mailFile.getFile(); if (!file.exists()) { continue; } DataSource dataSource = new FileDataSource(file); BodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(mailFile.getFileName()); multipart.addBodyPart(attachmentBodyPart); } } jxMessage.setContent(multipart); return jxMessage; }
From source file:com.clustercontrol.notify.util.SendMail.java
public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ??/*from w ww . j a v a 2 s. c om*/ return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } // BCC if (bccAddressStr != null) { InternetAddress[] bccAddress = this.getAddress(bccAddressStr); if (bccAddress != null && bccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } if (bccAddressStr != null) { message += ", BCC=" + Arrays.asList(bccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
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.//from w w w .ja v a2s.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: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 * //w w w . ja v a 2s . 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:GUI.DashbordAdminFrame.java
private void btnEnvMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvMailActionPerformed // TODO add your handling code here: String to = null;/*from w w w . java 2s.c o m*/ UserDao u = new UserDao(); List listeTo = new ArrayList(); listeTo = u.findAllEmail(); String from = "allfordealpi@gmail.com"; final String username = "allfordealpi@gmail.com"; final String password = "pidev2016"; String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (Object o : listeTo) { to = (String) o; System.out.println(to); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(tfObjet.getText()); message.setText(taContenu.getText()); // Send message Transport.send(message); } System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//from ww w .ja v a 2 s .c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), "Unable to send the mail because the mail-server (SMTP host) is not specified"); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { protocol = "smtps"; } props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); String email_address = StringUtil.environmentSubstitute(replyAddress); if (!Const.isEmpty(email_address)) { msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException("reply e-mail address is not filled in"); } // Split the mail-address: space separated String destinations[] = StringUtil.environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } msg.setSubject(StringUtil.environmentSubstitute(subject)); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append("Job:").append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append("Name : ").append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append("Directory : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append("JobEntry : ").append(getName()).append(Const.CR); messageText.append(Const.CR); } if (includeDate) { Value date = new Value("date", new Date()); messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append("Previous result:").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append("Job entry nr : ").append(result.getEntryNr()).append(Const.CR); messageText.append("Errors : ").append(result.getNrErrors()).append(Const.CR); messageText.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR); messageText.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR); messageText.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR); messageText.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR); messageText.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR); messageText.append("Script exit status : ").append(result.getExitStatus()).append(Const.CR); messageText.append("Result : ").append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson)) || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) { messageText.append("Contact information :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson)) .append(Const.CR); messageText.append("Telephone number : ").append(StringUtil.environmentSubstitute(contactPhone)) .append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append("Path to this job entry:").append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List resultFiles = result.getResultFilesList(); if (resultFiles != null && resultFiles.size() > 0) { if (!zipFiles) { // Add all files to the message... // for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + StringUtil.environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getURI()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { //System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {//w ww. j av a2s .c o m String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); 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"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); String mailTos = ""; List dlIds = sInfo.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(biobj, 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.auth", "true"); // create autheticator object Authenticator auth = new SMTPAuthenticator(user, pass); // open session Session session = Session.getDefaultInstance(props, auth); // 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 = biobj.getName() + toBeAppendedToName; 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(response, retCT, biobj.getName() + toBeAppendedToName + fileExt); 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 Transport.send(msg); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); } finally { logger.debug("OUT"); } }