List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java
protected void generateMail(String destination, String copy, String title, String content) throws NamingException, MessagingException { InitialContext ic = new InitialContext(); Session session = (Session) ic.lookup(getJavaMailJndiName()); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false)); if (!isBlank(copy)) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false)); }/* w ww. jav a 2 s .c o m*/ msg.setSubject(title, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content, "text/html; charset=utf-8"); Transport.send(msg); }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }/*from www . j a v a 2 s . co m*/ Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java
private Result sendMail(MCPackageMail mcPackageMail) { try {//from w ww .j a v a2s.com Map<String, String> statusAction = new HashMap<>(); statusAction.put("NEW", "released"); statusAction.put("CANCEL", "withdrawn"); statusAction.put("UPDATE", "updated"); String html = mcPackageMail.getMail(); ArrayList<String> to = new ArrayList<>(); to.add(mcPackageMail.getDestination()); String from = mcPackageMail.getSource(); String host = Configuration.getInstance().getSmtpHost(); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.localhost", host); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (String s : to) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(s)); } System.out.println("Destination: " + Arrays.asList(to).toString()); message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", "")); message.setContent(html, "text/html"); Transport.send(message); System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-" + mcPackageMail.getPackageVersion() + " was succesfully sent!"); } catch (Exception ex) { Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex); result.setResultCode("1"); result.setResultMessage(ex.getMessage()); } return result; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser, ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpEmailFrom"); }/*from ww w. ja v a2s .com*/ smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:com.intranet.intr.proveedores.EmpControllerGestion.java
public void enviarProvUC(proveedores proveedor) { String cuerpo = ""; String servidorSMTP = "smtp.1and1.es"; String puertoEnvio = "465"; Properties props = new Properties();//propiedades a agragar props.put("mail.smtp.user", miCorreo);//correo origen props.put("mail.smtp.host", servidorSMTP);//tipo de servidor props.put("mail.smtp.port", puertoEnvio);//puesto de salida props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor props.put("mail.smtp.auth", "true");//autentificacion props.put("mail.smtp.password", "angel2010");//autentificacion props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); SecurityManager security = System.getSecurityManager(); Authenticator auth = new autentificadorSMTP();//autentificar el correo Session session = Session.getInstance(props, auth);//se inica una session // session.setDebug(true); try {/*from w w w .jav a2s . c o m*/ // Creamos un objeto mensaje tipo MimeMessage por defecto. MimeMessage mensajeE = new MimeMessage(session); // Asignamos el de o from? al header del correo. mensajeE.setFrom(new InternetAddress(miCorreo)); // Asignamos el para o to? al header del correo. mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail())); // Asignamos el asunto mensajeE.setSubject("Su Perfil Personal"); // Creamos un cuerpo del correo con ayuda de la clase BodyPart //BodyPart cuerpoMensaje = new MimeBodyPart(); // Asignamos el texto del correo String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: " + proveedor.getContrasenna() + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm"; // Asignamos el texto del correo cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>"; mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>", "text/html"); //mensaje.setText(text); // Creamos un multipart al correo // Enviamos el correo Transport.send(mensajeE); System.out.println("Mensaje enviado"); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:org.kite9.diagram.server.AbstractKite9Controller.java
public void sendErrorEmail(Throwable t, String xml, String url) { try {// www.j a va 2 s .c om Properties props = new Properties(); props.put("mail.smtp.host", "server.kite9.org"); Session session = Session.getInstance(props); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("servicetest@kite9.com")); msg.setRecipient(RecipientType.TO, new InternetAddress("rob@kite9.com")); String name = ctx.getServletContextName(); boolean local = isLocal(); msg.setSubject("Failure in " + (local ? "TEST" : name) + " Service: " + this.getClass().getName()); StringWriter sw = new StringWriter(10000); PrintWriter pw = new PrintWriter(sw); pw.write("URL: " + url + "\n"); t.printStackTrace(pw); if (xml != null) { pw.println(); pw.print(xml); } pw.close(); msg.setText(sw.toString()); Transport.send(msg); } catch (Exception e) { } finally { t.printStackTrace(); } }
From source file:org.springfield.lou.application.types.EuscreenxlitemApplication.java
public void sendContentProviderMail(Screen s, String data) { //System.out.println("Send mail to CP: " + data); JSONObject form = (JSONObject) JSONValue.parse(data); String mailfrom = "euscreen-portal@noterik.nl"; String mailsubject = "Somebody showed interest in your item on EUScreen"; String email = (String) form.get("email"); String id = (String) form.get("identifier"); String provider = (String) form.get("provider"); String subject = (String) form.get("subject"); String title = (String) form.get("title"); String message = (String) form.get("message"); message = message.replaceAll("(\r\n|\n)", "<br />"); //Form validation JSONObject mailResponse = new JSONObject(); Set<String> keys = form.keySet(); boolean errors = false; for (String key : keys) { String value = (String) form.get(key); if (value == null || value.isEmpty()) { errors = true;//from w w w . ja v a2 s. co m break; } } if (errors) { mailResponse.put("status", "false"); mailResponse.put("message", "Please fill in all the fields."); s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")"); return; } String toemail = null; //Find the provider email FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default"); toemail = providerNode.getProperty("email"); String body = "Identifier: " + id + "<br/>"; body += "Title: " + title + "<br/>"; body += "Link to item on EUScreen:<br/>"; body += "<a href=\"http://euscreen.eu/item.html?id=" + id + "\">http://euscreen.eu/item.html?id=" + id + "</a><br/>"; body += "-------------------------------------------<br/><br/>"; body += "Subject: " + subject + "<br/>"; body += "Message:<br/>"; body += message + "<br/><br/>"; body += "-------------------------------------------<br/>"; body += "You can contact the sender of this message on: <a href=\"mailto:" + email + "\">" + email + "</a><br/>"; if (this.inDevelMode()) { //In devel mode always send the email to the one filled in the form toemail = email; } //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed //toemail = email; boolean success = true; if (toemail != null) { try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); Session session = (Session) envCtx.lookup("mail/Session"); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mailfrom)); InternetAddress to[] = new InternetAddress[1]; to[0] = new InternetAddress(toemail); msg.setRecipients(Message.RecipientType.TO, to); InternetAddress bcc[] = new InternetAddress[1]; bcc[0] = new InternetAddress("r.rozendal@noterik.nl"); msg.setRecipients(Message.RecipientType.BCC, bcc); msg.setSubject(mailsubject); msg.setContent(body, "text/html"); Transport.send(msg); } catch (Exception e) { System.out.println("Failed sending email: " + e); success = false; } } else { success = false; } String response = "Your message has been successfuly sent."; if (!success) response = "There was a problem sending your mail.<br/>Please try again later."; mailResponse.put("status", Boolean.toString(success)); mailResponse.put("message", response); s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")"); }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }/* w ww . j a va 2 s .c o m*/ // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this method * will generate an email message that includes subject, message and * attachments to the recipient list. You can use the convenience * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i> * and <i>createAttachmentList()</i> for parameter building assistance. * * @param aFromAddress Source email address. * @param aRecipientList List of recipient email addresses. * @param aSubject Subject of the email message. * @param aMessage Messsage.// w ww.j a v a 2s . c o m * @param anAttachmentFiles List of file attachments or <i>null</i> for none. * * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a> * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a> * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage, ArrayList<String> anAttachmentFiles) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0) && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); Message mimeMessage = new MimeMessage(mMailSession); internetAddressFrom = new InternetAddress(aFromAddress); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); for (String mailAddressTo : aRecipientList) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } mimeMessage.setSubject(aSubject); // The following logic create a multi-part message and adds the attachment to it. BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(aMessage); // messageBodyPart.setContent(aMessage, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) { for (String pathFileName : anAttachmentFiles) { File attachmentFile = new File(pathFileName); if (attachmentFile.exists()) { messageBodyPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(pathFileName); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); multipart.addBodyPart(messageBodyPart); } } appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage)); } else appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); mimeMessage.setContent(multipart); Transport.send(mimeMessage); } else throw new NSException("Valid from, recipient, subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
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()); }// w w w .ja va 2 s.com 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(); }