List of usage examples for javax.mail Session getDefaultInstance
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator)
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.// w w w . j a v a2s . com * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Open mail session with the SMTP server using the given credentials. Will * use no authentication if strUsername is null or blank. * * @param strHost The SMTP name or IP address. * @param nPort The port to use//from w w w.ja v a 2 s .co m * @param strUsername the username * @param strPassword the password * @return the mails session object */ protected static Session getMailSession(String strHost, int nPort, final String strUsername, final String strPassword) { String strDebug = AppPropertiesService.getProperty(PROPERTY_MAIL_SESSION_DEBUG, Boolean.FALSE.toString()); boolean bSessionDebug = Boolean.parseBoolean(strDebug); // Initializes a mail session with the SMTP server Properties props = System.getProperties(); props.put(MAIL_HOST, strHost); props.put(MAIL_TRANSPORT_PROTOCOL, SMTP); props.put(MAIL_PROPTOCOL_HOST, strHost); props.put(MAIL_PROPTOCOL_PORT, nPort); Authenticator auth; if (StringUtils.isNotBlank(strUsername)) { props.put(MAIL_SMTP_AUTH, TRUE); // using authenticator class that return a PasswordAuthentication auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUsername, strPassword); } }; } else { // no authentication data provided, no authenticator auth = null; } Session mailSession = Session.getDefaultInstance(props, auth); // Activate debugging mailSession.setDebug(bSessionDebug); return mailSession; }
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()); }/* ww w . java 2 s . c om*/ 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:trendplot.TrendPlot.java
private void emailResults() throws IOException, WebUtilException { emailStart = System.currentTimeMillis(); ViewerConfig vc = new ViewerConfig(); if (!config.isEmpty()) { vc.setConfigFileName(config);/*from w ww. ja va 2 s .co m*/ } vc.readConfig(); String host = vc.get("webserver"); if (host == null || host.isEmpty()) { host = "ldvw.ligo.caltech.edu"; } String servlet = vc.get("servlet"); if (servlet == null || servlet.isEmpty()) { servlet = "ldvw/view"; } PageItemList msg = new PageItemList(); if (!imgIds.isEmpty()) { msg.add(new PageItemHeader("The following results are available:", 3)); PageTable tbl = new PageTable(); for (int img = 0; img < imgIds.size(); img++) { PageTableRow row = new PageTableRow(); row.add(descriptions.get(img)); Integer imgId = imgIds.get(img); String url = "https://" + host + "/" + servlet + "?act=getimg&imgId=" + imgId.toString(); PageItemTextLink link = new PageItemTextLink(url, "link"); row.add(link); tbl.addRow(row); } msg.add(tbl); msg.addBlankLines(2); String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group); msg.add(new PageItemString(groupIntro, false)); String groupUrl = String.format( "https://%1$s/%2$s?act=imagehistory&group=%3$s" + "&usrSel=%4$s", host, servlet, group, user); PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page."); msg.add(groupLink); msg.addBlankLines(2); } else if (!checkOnly) { msg.add("Sorry but no images were produced."); msg.addBlankLines(2); } if (verbose || imgIds.isEmpty()) { msg.add(new PageItemString("<br>Stdout:<br><br>", false)); String outText = outStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); msg.add(new PageItemString("<br>Stderr:<br><br>", false)); outText = errStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); } msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false)); Float condor = (startTime - qtime) / 1000.f; String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor); Float overhead = (transferStart - startTime) / 1000.f; Float xfer = (plotStart - transferStart) / 1000.f; Float plot = (emailStart - plotStart) / 1000.f; String timing = String.format( "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds", condorTime, overhead, xfer, plot); outPrintWriter.println(timing); msg.addBlankLines(2); msg.add(new PageItemString(timing, false)); msg.addBlankLines(1); String msgText = msg.getHtml(); Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try { //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject("Trend plot results are available."); message.setText(msgText, "utf-8", "html"); Transport.send(message); outPrintWriter.format("Email sent to %1$s\n", email); errPrintWriter.println("Email message:"); errPrintWriter.println(msgText); } catch (MessagingException ex) { throw new WebUtilException("Cannot send email. " + ex); } }
From source file:trendplot.TrendPlot.java
private void testEmail() { Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try {//from w w w. ja va 2 s . c om //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); String email = "joe@areeda.com"; message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); String msg = "<h3>this is a test</h3>"; message.setSubject("Test email"); message.setText(msg, "utf-8", "html"); Transport.send(message); System.out.format("Email sent to %1$s\n", email); } catch (MessagingException ex) { System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage()); } }
From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java
private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed // TODO add your handling code here: int selectedRow = productTable.getSelectedRow(); if (selectedRow < 0) { JOptionPane.showMessageDialog(null, "Please select a Product from the Table"); return;/*from w w w . ja v a2 s.c o m*/ } Product product = (Product) productTable.getValueAt(selectedRow, 0); int quantity = (Integer) quantitySpinner.getValue(); if (quantity == 0) { JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!"); return; } if (product != null) { updateQuantity(product, quantity, SUBTRACT); } String medName = product.getProdName(); Employee patient = (Employee) patientCombo1.getSelectedItem(); patient.getMedicalRecord().setMedicinePrescribed(medName); String email = patient.getEmail(); if (email.trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!"); return; } if (isValidEmailAddress(email)) { String uuid = UUID.randomUUID().toString(); //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample"); Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24"); } } ); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("neelzsaxena@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Prescribed Medicines"); message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:" + quantity + '\n' + "The unique barcode is:" + uuid); Transport.send(message); populateTable(); JOptionPane.showMessageDialog(null, "message sent"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "message failed"); } } else { JOptionPane.showMessageDialog(null, "Invalid Email Id"); return; } // String uuid = UUID.randomUUID().toString(); // //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample"); // // Properties props = new Properties(); // props.put("mail.smtp.host", "smtp.gmail.com"); // props.put("mail.smtp.socketFactory.port", "465"); // props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.auth", "true"); // props.put("mail.smtp.port", "465"); // // Session session = Session.getDefaultInstance(props, // new javax.mail.Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication(){ // return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24"); // } // // } // // ); // try{ // Message message = new MimeMessage(session); // message.setFrom(new InternetAddress("neelzsaxena@gmail.com")); // message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); // message.setSubject("Prescribed Medicines"); // message.setText("The medicine Prescribed is :" +medName + '\n'+ // "The Quantity authorized is:"+quantity + '\n'+ // "The unique barcode is:"+uuid); // Transport.send(message); // populateTable(); // JOptionPane.showMessageDialog(null,"message sent"); // }catch(Exception e){ // JOptionPane.showMessageDialog(null,"message failed"); // } }
From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT, String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {//from w w w . jav a2 s .c om String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); 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 = sInfo.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false); String mailTxt = sInfo.getMailTxt(); String[] recipients = findRecipients(sInfo, biobj, dataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", 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"); session = Session.getDefaultInstance(props, auth); logger.error("Session.getDefaultInstance(props, auth)"); } else { session = Session.getDefaultInstance(props); logger.error("Session.getDefaultInstance(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 + " " + biobj.getName() + toBeAppendedToName; msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription); // 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:UserInfo_Frame.java
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port ", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587"); }//from ww w. j a va 2 s .com }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com")); message.setSubject("hi this is me"); message.setText("hi how are you, i am fine"); Transport.send(message); JOptionPane.showMessageDialog(null, "message sent"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } }
From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java
public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from ww w. j a va 2 s . 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 new RuntimeException("sendMail: " + e.toString()); } } else { throw new RuntimeException("The function call sendMail requires 5 arguments."); } }
From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java
public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object 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 a v a2s.c om*/ // 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 new RuntimeException("sendMail: " + e.toString()); } } else { throw new RuntimeException("The function call sendMail requires 5 arguments."); } }