List of usage examples for javax.mail Transport sendMessage
public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
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 w w w . j a v a2s . c om*/ // 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:org.sakaiproject.email.impl.BasicEmailService.java
/** * {@inheritDoc}/*from ww w . j a va2 s . co m*/ */ public void sendToUsers(Collection<User> users, Collection<String> headers, String message) { if (headers == null) { M_log.warn("sendToUsers: null headers"); return; } if (m_testMode) { M_log.info("sendToUsers: users: " + usersToStr(users) + " headers: " + listToStr(headers) + " message:\n" + message); return; } if (m_smtp == null) { M_log.warn("sendToUsers: smtp not set"); return; } if (users == null) { M_log.warn("sendToUsers: null users"); return; } if (message == null) { M_log.warn("sendToUsers: null message"); return; } // form the list of to: addresses from the users users collection ArrayList<InternetAddress> addresses = new ArrayList<InternetAddress>(); for (User user : users) { String email = user.getEmail(); if ((email != null) && (email.length() > 0)) { try { addresses.add(new InternetAddress(email)); } catch (AddressException e) { if (M_log.isDebugEnabled()) M_log.debug("sendToUsers: " + e); } } } // if we have none if (addresses.isEmpty()) return; // how many separate messages do we need to send to keep each one at or under m_maxRecipients? int numMessageSets = ((addresses.size() - 1) / m_maxRecipients) + 1; // make an array for each and store them all in the collection ArrayList<Address[]> messageSets = new ArrayList<Address[]>(); int posInAddresses = 0; for (int i = 0; i < numMessageSets; i++) { // all but the last one are max size int thisSize = m_maxRecipients; if (i == numMessageSets - 1) { thisSize = addresses.size() - ((numMessageSets - 1) * m_maxRecipients); } // size an array Address[] toAddresses = new Address[thisSize]; messageSets.add(toAddresses); // fill the array int posInToAddresses = 0; while (posInToAddresses < thisSize) { toAddresses[posInToAddresses] = (Address) addresses.get(posInAddresses); posInToAddresses++; posInAddresses++; } } // get a session for our smtp setup, include host, port, reverse-path, and set partial delivery Properties props = createMailSessionProperties(); Session session = Session.getInstance(props); // form our Message MimeMessage msg = new MyMessage(session, headers, message); // fix From and ReplyTo if necessary checkFrom(msg); // transport the message long time1 = 0; long time2 = 0; long time3 = 0; long time4 = 0; long time5 = 0; long time6 = 0; long timeExtraConnect = 0; long timeExtraClose = 0; long timeTmp = 0; int numConnects = 1; try { if (M_log.isDebugEnabled()) time1 = System.currentTimeMillis(); Transport transport = session.getTransport(protocol); if (M_log.isDebugEnabled()) time2 = System.currentTimeMillis(); msg.saveChanges(); if (M_log.isDebugEnabled()) time3 = System.currentTimeMillis(); if (m_smtpUser != null && m_smtpPassword != null) transport.connect(m_smtp, m_smtpUser, m_smtpPassword); else transport.connect(); if (M_log.isDebugEnabled()) time4 = System.currentTimeMillis(); // loop the send for each message set for (Iterator<Address[]> i = messageSets.iterator(); i.hasNext();) { Address[] toAddresses = i.next(); try { transport.sendMessage(msg, toAddresses); // if we need to use the connection for just one send, and we have more, close and re-open if ((m_oneMessagePerConnection) && (i.hasNext())) { if (M_log.isDebugEnabled()) timeTmp = System.currentTimeMillis(); transport.close(); if (M_log.isDebugEnabled()) timeExtraClose += (System.currentTimeMillis() - timeTmp); if (M_log.isDebugEnabled()) timeTmp = System.currentTimeMillis(); transport.connect(); if (M_log.isDebugEnabled()) { timeExtraConnect += (System.currentTimeMillis() - timeTmp); numConnects++; } } } catch (SendFailedException e) { if (M_log.isDebugEnabled()) M_log.debug("sendToUsers: " + e); } catch (MessagingException e) { M_log.warn("sendToUsers: " + e); } } if (M_log.isDebugEnabled()) time5 = System.currentTimeMillis(); transport.close(); if (M_log.isDebugEnabled()) time6 = System.currentTimeMillis(); } catch (MessagingException e) { M_log.warn("sendToUsers:" + e); } // log if (M_log.isInfoEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("sendToUsers: headers["); for (String header : headers) { buf.append(" "); buf.append(cleanUp(header)); } buf.append("]"); for (Address[] toAddresses : messageSets) { buf.append(" to[ "); for (int a = 0; a < toAddresses.length; a++) { buf.append(" "); buf.append(toAddresses[a]); } buf.append("]"); } if (M_log.isDebugEnabled()) { buf.append(" times[ "); buf.append(" getransport:" + (time2 - time1) + " savechanges:" + (time3 - time2) + " connect(#" + numConnects + "):" + ((time4 - time3) + timeExtraConnect) + " send:" + (((time5 - time4) - timeExtraConnect) - timeExtraClose) + " close:" + ((time6 - time5) + timeExtraClose) + " total: " + (time6 - time1) + " ]"); } M_log.info(buf.toString()); } }
From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//from ww w. j a va 2 s .co m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", 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); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = 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[] = 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[] = 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); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(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(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .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 if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { 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(file.getName().getBaseName()); // 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 + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { 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().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); 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(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), 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:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;/*from w ww. ja va 2 s . co m*/ // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) { props.put("mail." + protocol + ".port", environmentSubstitute(port)); } if (log.isDebug()) { 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(log.isDebug()); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", sensitivity); // Possible values are normal, personal, private, company-confidential } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) { sender_address = sender_name + '<' + sender_address + '>'; } msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = 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); String realCC = environmentSubstitute(getDestinationCc()); if (!Const.isEmpty(realCC)) { // Split the mail-address Cc: space separated String[] destinationsCc = realCC.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); } String realBCc = environmentSubstitute(getDestinationBCc()); if (!Const.isEmpty(realBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realBCc.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); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); String endRow = isUseHTML() ? "<br>" : Const.CR; String realComment = environmentSubstitute(comment); if (!Const.isEmpty(realComment)) { messageText.append(realComment).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow); messageText.append("-----").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + " : ") .append(getName()).append(endRow); messageText.append(Const.CR); } if (includeDate) { messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow); } if (!onlySendComment && result != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":") .append(endRow); messageText.append("-----------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + " : ") .append(result.getNrLinesRejected()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(endRow); messageText.append(endRow); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :") .append(endRow); messageText.append("---------------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(endRow); messageText.append(endRow); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":") .append(endRow); messageText.append("------------------------").append(endRow); addBacktracking(jobTracker, messageText); if (isUseHTML()) { messageText.replace(0, messageText.length(), messageText.toString().replace(Const.CR, endRow)); } } } MimeMultipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // Attached files counter int nrattachedFiles = 0; // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { 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(file.getName().getBaseName()); // insist on base64 to preserve line endings files.addHeader("Content-Transfer-Encoding", "base64"); // add the part with the file in the BodyPart(); parts.addBodyPart(files); nrattachedFiles++; logBasic("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 + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { 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().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); try { int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } } finally { inputStream.close(); } zipOutputStream.closeEntry(); nrattachedFiles++; logBasic("Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { logError("Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { logError("Unable to close attachement zip file archive : " + e.toString()); logError(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 the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } int nrEmbeddedImages = 0; if (embeddedimages != null && embeddedimages.length > 0) { FileObject imageFile = null; for (int i = 0; i < embeddedimages.length; i++) { String realImageFile = environmentSubstitute(embeddedimages[i]); String realcontenID = environmentSubstitute(contentids[i]); if (messageText.indexOf("cid:" + realcontenID) < 0) { if (log.isDebug()) { log.logDebug("Image [" + realImageFile + "] is not used in message body!"); } } else { try { boolean found = false; imageFile = KettleVFS.getFileObject(realImageFile, this); if (imageFile.exists() && imageFile.getType() == FileType.FILE) { found = true; } else { log.logError("We can not find [" + realImageFile + "] or it is not a file"); } if (found) { // Create part for the image MimeBodyPart messageBodyPart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(imageFile.getURL()); messageBodyPart.setDataHandler(new DataHandler(fds)); // Setting the header messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">"); // Add part to multi-part parts.addBodyPart(messageBodyPart); nrEmbeddedImages++; log.logBasic("Image '" + fds.getName() + "' was embedded in message."); } } catch (Exception e) { log.logError( "Error embedding image [" + realImageFile + "] in message : " + e.toString()); log.logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (imageFile != null) { try { imageFile.close(); } catch (Exception e) { /* Ignore */ } } } } } } if (nrEmbeddedImages > 0 && nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file parts.setSubType("related"); } // put all parts together msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); String authPass = getPassword(authenticationPassword); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } } catch (IOException e) { logError("Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { logError("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) { logError(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { logError(" " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logError(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { logError(" " + 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++) { logError(" " + 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:org.opens.emailsender.EmailSender.java
/** * * @param emailFrom/*from w w w . j a va 2 s . com*/ * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.error("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.error("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn(ex.getMessage()); } } catch (NoSuchProviderException e) { LOGGER.warn(e.getMessage()); } catch (MessagingException e) { LOGGER.warn(e.getMessage()); } }
From source file:org.asqatasun.emailsender.EmailSender.java
/** * * @param emailFrom//from w w w .j a v a2s . c o m * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.debug("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.debug("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn("AddressException " + ex.getMessage()); LOGGER.warn("AddressException " + ex.getStackTrace()); } } catch (NoSuchProviderException e) { LOGGER.warn("NoSuchProviderException " + e.getMessage()); LOGGER.warn("NoSuchProviderException " + e.getStackTrace()); } catch (MessagingException e) { LOGGER.warn("MessagingException " + e.getMessage()); LOGGER.warn("MessagingException " + e.getStackTrace()); } }
From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format).// ww w.j a v a2s. c o m * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int send(Mail mail) { Session session = null;//from w w w .ja v a 2 s . c om Transport transport = null; if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo())) && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc())) && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) { logger.error("This mail has no recipient"); return 0; } if (mail.getContents().size() == 0) { logger.error("This mail is empty. You should add a content"); return 0; } try { if ((transport == null) || (session == null)) { logger.info("Sending mail : Initializing properties"); Properties props = initProperties(); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (session.getProperty("mail.smtp.auth") == "true") transport.connect(session.getProperty("mail.smtp.server.username"), session.getProperty("mail.smtp.server.password")); else transport.connect(); try { Multipart wrapper = generateMimeMultipart(mail); InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo()); MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setSubject(mail.getSubject()); message.setFrom(new InternetAddress(mail.getFrom())); message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo); if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) { logger.info("Adding ReplyTo field"); InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo()); if (adressesReplyTo.length != 0) message.setReplyTo(adressesReplyTo); } if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) { logger.info("Adding Cc recipients"); InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc()); if (adressesCc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc); } if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) { InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc()); if (adressesBcc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc); } message.setContent(wrapper); message.setSentDate(new Date()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (SendFailedException sfex) { logger.error("Error encountered while trying to send the mail"); logger.error("SendFailedException has occured.", sfex); try { transport.close(); } catch (MessagingException Mex) { logger.error("MessagingException has occured.", Mex); } return 0; } catch (MessagingException mex) { logger.error("Error encountered while trying to send the mail"); logger.error("MessagingException has occured.", mex); try { transport.close(); } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } } } catch (Exception e) { System.out.println(e.toString()); logger.error("Error encountered while trying to setup mail properties"); try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } return 1; }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom, String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost String host = ConfigManager.getInstance().getSmtpMailhost(); String port = ConfigManager.getInstance().getSmtpMailport(); String password = ConfigManager.getInstance().getSmtpMailpassword(); String auth = ConfigManager.getInstance().getSmtpMailauth(); String sender = ConfigManager.getInstance().getSmtpMailuser(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.user", sender); properties.setProperty("mail.smtp.password", password); properties.setProperty("mail.smtp.auth", auth); properties.setProperty("mail.smtp.port", port); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. if (!StringUtils.isBlank(sender)) { try {/* w ww.ja v a 2 s .c o m*/ message.setFrom(new InternetAddress(sender)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex); } } List<Address> addresses = new ArrayList<Address>(); String receivers = emails.getReceivers(); receivers = StringUtils.trim(receivers); for (String receiver : receivers.split(";")) { if (!StringUtils.isBlank(receiver)) { try { addresses.add(new InternetAddress(receiver)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex); } } } Address[] add = new Address[addresses.size()]; addresses.toArray(add); try { message.addRecipients(Message.RecipientType.TO, add); // Set Subject: header field message.setSubject("[Pundit Contact Form]: " + subject); // Now set the actual message message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n" + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex); } // Send message try { logger.log(Level.INFO, "Trying to send message to receivers: {0}", Arrays.toString(message.getAllRecipients())); transport = session.getTransport("smtp"); transport.connect(host, sender, password); transport.sendMessage(message, message.getAllRecipients()); logger.log(Level.INFO, "Sent messages to all receivers {0}", Arrays.toString(message.getAllRecipients())); } catch (NoSuchProviderException nspe) { logger.log(Level.SEVERE, "Cannot find smtp provider", nspe); } catch (MessagingException me) { logger.log(Level.SEVERE, "Cannot set transport layer ", me); } finally { try { transport.close(); } catch (MessagingException ex) { } catch (NullPointerException ne) { } } }
From source file:library.Form_Library.java
License:asdf
public void sendFromGMail(String from, String pass, String to, String subject, String body) { this.taBaoCao.append("Sent to " + to + " successfully.\n"); Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try {//from w w w.java2s. c o m message.setFrom(new InternetAddress(from)); InternetAddress toAddress = new InternetAddress(); // To get the array of addresses // for( int i = 0; i < to.length; i++ ) { toAddress = new InternetAddress(to); // } // for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress); // } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); System.out.print("Successfully Sent" + "\n"); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } }