List of usage examples for javax.mail Session getDefaultInstance
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator)
From source file:com.photon.phresco.util.Utility.java
public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }/*from w w w. j ava2 s . c o m*/ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); DataSource source = new FileDataSource(body); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("Error.txt"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source2 = new FileDataSource(screen); messageBodyPart2.setDataHandler(new DataHandler(source2)); messageBodyPart2.setFileName("Error.jpg"); multipart.addBodyPart(messageBodyPart2); MimeBodyPart mainPart = new MimeBodyPart(); String content = "<b>Phresco framework error report<br><br>User Name: " + user + "<br> Email Address: " + fromAddr + "<br>Build No: " + build; mainPart.setContent(content, "text/html"); multipart.addBodyPart(mainPart); message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {/* w ww . j av a 2s . c o m*/ //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String strArrRecipients[] = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent((String) ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw Context.reportRuntimeError("sendMail: " + e.toString()); } } else { throw Context.reportRuntimeError("The function call sendMail requires 5 arguments."); } }
From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from w w w . j av a 2 s . co m // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String[] strArrRecipients = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent(ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw Context.reportRuntimeError("sendMail: " + e.toString()); } } else { throw Context.reportRuntimeError("The function call sendMail requires 5 arguments."); } }
From source file:com.photon.phresco.util.Utility.java
public static void sendNewPassword(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }/*from w ww . ja v a 2 s .com*/ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); message.setContent(body, "text/html"); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
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 {//from w w w . j a va 2s .co 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"); } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
/** * /*from w ww . j a v a2s.com*/ * @param bounceAdress must be a raw email, without anything else (no "bla bli <bla@bli.ch>" !) * @return */ private MimeMessage createMessage(Address bounceAdress) { String mailhost = WebappHelper.getMailConfig("mailhost"); String mailhostTimeout = WebappHelper.getMailConfig("mailTimeout"); boolean sslEnabled = Boolean.parseBoolean(WebappHelper.getMailConfig("sslEnabled")); boolean sslCheckCertificate = Boolean.parseBoolean(WebappHelper.getMailConfig("sslCheckCertificate")); Authenticator smtpAuth; if (WebappHelper.isMailHostAuthenticationEnabled()) { String smtpUser = WebappHelper.getMailConfig("smtpUser"); String smtpPwd = WebappHelper.getMailConfig("smtpPwd"); smtpAuth = new MailerSMTPAuthenticator(smtpUser, smtpPwd); } else { smtpAuth = null; } Properties p = new Properties(); p.put("mail.smtp.from", bounceAdress.toString()); p.put("mail.smtp.host", mailhost); p.put("mail.smtp.timeout", mailhostTimeout); p.put("mail.smtp.connectiontimeout", mailhostTimeout); p.put("mail.smtp.ssl.enable", sslEnabled); p.put("mail.smtp.ssl.checkserveridentity", sslCheckCertificate); Session mailSession; if (smtpAuth == null) { mailSession = javax.mail.Session.getInstance(p); } else { // use smtp authentication from configuration p.put("mail.smtp.auth", "true"); mailSession = Session.getDefaultInstance(p, smtpAuth); } if (isLogDebugEnabled()) { // enable mail session debugging on console mailSession.setDebug(true); } return new MimeMessage(mailSession); }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java
public void sendEmail(String subject, String text, String toEmail) { // Recipient's email ID needs to be mentioned. String to = toEmail;/*from w w w.j a v a2 s.c o m*/ // Sender's email ID needs to be mentioned String from = "flimplatereader@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties // Properties properties = System.getProperties(); Properties properties = System.getProperties(); // Setup mail server //properties.setProperty("mail.smtp.host", "10.101.3.229"); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.setProperty("mail.user", "flimplatereader"); properties.setProperty("mail.password", "flimimages"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); //enable authentication final String pww = "flimimages"; Session session; session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(text); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:org.kuali.test.utils.Utils.java
/** * //from w ww .j a va 2s . c o m * @param configuration * @param overrideEmail * @param testSuite * @param testHeader * @param testResults * @param errorCount * @param warningCount * @param successCount */ public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration, String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults, int errorCount, int warningCount, int successCount) { if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress()) && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) { String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader); if (toAddresses.length > 0) { Properties props = new Properties(); props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost()); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress())); if (StringUtils.isBlank(overrideEmail)) { for (String recipient : toAddresses) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } else { StringTokenizer st = new StringTokenizer(overrideEmail, ","); while (st.hasMoreTokens()) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken())); } } StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject()); subject.append(" - Platform: "); if (testSuite != null) { subject.append(testSuite.getPlatformName()); subject.append(", TestSuite: "); subject.append(testSuite.getName()); } else { subject.append(testHeader.getPlatformName()); subject.append(", Test: "); subject.append(testHeader.getTestName()); } subject.append(" - [errors="); subject.append(errorCount); subject.append(", warnings="); subject.append(warningCount); subject.append(", successes="); subject.append(successCount); subject.append("]"); msg.setSubject(subject.toString()); StringBuilder msgtxt = new StringBuilder(256); msgtxt.append("Please see test output in the following attached files:\n"); for (File f : testResults) { msgtxt.append(f.getName()); msgtxt.append("\n"); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgtxt.toString()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); for (File f : testResults) { if (f.exists() && f.isFile()) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.setDataHandler(new DataHandler(new FileDataSource(f))); mbp2.setFileName(f.getName()); mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException ex) { LOG.warn(ex.toString(), ex); } } } }
From source file:FirstStatMain.java
private void btnsendemailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsendemailActionPerformed final String senderemail = txtEmailfrom.getText(); final String sendPass = txtPassword.getText(); String send_to = txtEmailto.getText(); String email_sub = txtemailsbj.getText(); String email_body = tABody.getText(); Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() { @Override/*from ww w . ja va 2 s. c om*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderemail, sendPass); } }); try { /* Message Header*/ Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderemail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(send_to)); message.setSubject(email_sub); /*setting text message*/ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(email_body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); /*attaching file*/ messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file_path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(txtattachmentname.getText()); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); JOptionPane.showMessageDialog(rootPane, "Message sent"); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e); } }