List of usage examples for javax.mail MessagingException printStackTrace
public void printStackTrace()
From source file:org.rhq.enterprise.server.core.EmailManagerBean.java
/** * Send email to the addressses passed in toAddresses with the passed subject and body. Invalid emails will * be reported back. This can only catch sender errors up to the first smtp gateway. * @param toAddresses list of email addresses to send to * @param messageSubject subject of the email sent * @param messageBody body of the email to be sent * * @return list of email receivers for which initial delivery failed. *///from ww w . j a v a2s.c o m public Collection<String> sendEmail(Collection<String> toAddresses, String messageSubject, String messageBody) { MimeMessage mimeMessage = new MimeMessage(mailSession); try { mimeMessage.setSubject(messageSubject); mimeMessage.setContent(messageBody, "text/plain"); } catch (MessagingException e) { e.printStackTrace(); // TODO: Customise this generated block return toAddresses; } Exception error = null; Collection<String> badAdresses = new ArrayList<String>(toAddresses.size()); // Send to each recipient individually, do not throw exceptions until we try them all for (String toAddress : toAddresses) { try { LOG.debug("Sending email [" + messageSubject + "] to recipient [" + toAddress + "]"); InternetAddress recipient = new InternetAddress(toAddress); Transport.send(mimeMessage, new InternetAddress[] { recipient }); } catch (Exception e) { LOG.error("Failed to send email [" + messageSubject + "] to recipient [" + toAddress + "]: " + e.getMessage()); badAdresses.add(toAddress); // Remember the first error - in case its due to a session initialization problem, // we don't want to lose the first error. if (error == null) { error = e; } } } if (error != null) { LOG.error("Sending of emails failed for this reason: " + error.getMessage()); } return badAdresses; }
From source file:com.unilever.audit.services2.ForgetPassword.java
@GET @Path("Email/{email}") @Produces("application/json") public String LoginIn(@PathParam("email") String email) throws IOException { boolean status = true; String error = null;//from w w w. ja v a2s. c o m JSONObject result = new JSONObject(); Map<String, Object> hm = new HashMap<String, Object>(); hm.put("email", email); Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST .findOneByQuery("Merchandisers.findByEmail", hm); if (merchidisers == null) { status = false; error = "invalid email"; } else { Properties props = new Properties(); final String from = ""; final String password = ""; props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.user", from); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.password", password); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); session.setDebug(true); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, email); msg.setSubject("Unilever Confirmation"); msg.setSentDate(new Date()); msg.setText(""); Transport.send(msg); } catch (MessagingException ex) { // status = false; // error="Error Sending Email"; ex.printStackTrace(); } } result.put("status", status); result.put("error", error); System.out.println("----------------" + result.toString()); return result.toString(); }
From source file:org.capelin.mvc.mail.SMTPMailSender.java
protected boolean send(String recipient, String body, boolean html) { Properties props = System.getProperties(); props.put("mail.smtp.host", serverName); Session session = Session.getInstance(props, null); props.put("mail.from", sender); Message msg = new MimeMessage(session); try {/*w w w . j av a2s . co m*/ msg.setSubject(subject); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false)); if (html) { msg.setContent(new String(body.getBytes(), "iso-8859-1"), "text/html; charset=iso-8859-1"); } else { msg.setText(body); } // Send the message: Transport.send(msg); log.debug("Email send to: " + sender); return true; } catch (MessagingException e) { log.info("Email Sending failed due to " + e); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }/*w ww. java 2s.co m*/ String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:com.third.rent.user.controller.LoginController.java
@RequestMapping(value = "/user/userseachpwd.do") public String userseachpwd(@RequestParam String userId, @RequestParam String userEmail, Model model) { logger.info("? ? userId={}, userEmail={}", userId, userEmail); UserVO userVo = new UserVO(); userVo.setUserId(userId);//from www.ja v a 2 s .co m userVo.setUserEmail(userEmail); /* String result = userService.selectSearchpwd(userVo); */ // id, email ? ? ?2 int count = userService.returnUserCount(userVo); logger.info("id, email ? ? count={}", count); String url = "/user/index.do", msg = ""; if (count > 0) { // ? 8? ? // char 33(!)~122(z) ? 8 String ramdomPwd = RandomStringUtils.randomAlphanumeric(8); logger.info(" ?? ramdomPwd={}", ramdomPwd); userVo.setUserPwd(ramdomPwd); userService.updateNewRandomPwd(userVo); String subject = "[3 ]" + userId + "? ?? ."; String content = " [ " + ramdomPwd + " ] - ? "; String receiver = userEmail; String sender = "admin@herbmall.com"; try { emailSender.sendEmail(subject, content, receiver, sender); logger.info("?? "); msg = " ?? ?."; } catch (MessagingException e) { logger.info("?? "); e.printStackTrace(); msg = " ?? ."; } } else { msg = " ID Email? ? ."; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; }
From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java
public void enviarEmailHtml(List<String> destinos, String msg, String titulo) { // Recipient's email ID needs to be mentioned. String to = ""; String rodape = "<br/><br/><br/><br/> <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">" + "Esta mensagem uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> " + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>" + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>" + "</div>"; for (String d : destinos) { if (d.equals(destinos.get(destinos.size() - 1))) { to = to.concat(d);//www . j av a 2s. c om } else { to = to.concat(d.concat(",")); } } // Sender's email ID needs to be mentioned String from = this.email; final String username = this.email;//change accordingly final String password = this.senha;//change accordingly Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", this.host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject(titulo); // Send the actual HTML message, as big as you like message.setContent(msg + rodape, "text/html"); // Send message Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); throw new RuntimeException(e); } }
From source file:org.emmanet.jobs.standAloneMailer.java
public void onSubmit() { /* String[] euCountriesList = {"Austria", "Belgium", "Bulgaria", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "United Kingdom"}; String[] assocCountriesList = {"Albania", "Croatia", "Iceland", "Israel", "Liechtenstein", "Macedonia", "Montenegro", "Norway", "Serbia", "Switzerland", "Turkey"}; Arrays.sort(euCountriesList);/*from w w w. j av a2 s. c o m*/ Arrays.sort(assocCountriesList);*/ //read from file try { BufferedReader in = new BufferedReader(new FileReader(Configuration.get("MAILCONTENT"))); String str; while ((str = in.readLine()) != null) { //content = content + str; content = (new StringBuilder()).append(content).append(str).toString(); } in.close(); } catch (IOException e) { e.printStackTrace(); } subject = "EMMAservice TA / impact assessment";//New Cre driver mouse lines" System.out.println("Subject: " + subject + "\n\nContent: " + content); //iterate over database email results adding to bcc use map keys ae address to prevent dups setCc(new HashMap()); //getCc().put(new String("emma@infrafrontier.eu"), ""); //getCc().put(new String("emma@infrafrontier.eu"), ""); // getCc().put(new String("sabine.fessele@helmholtz-muenchen.de"), ""); getCc().put(new String("michael.hagn@helmholtz-muenchen.de"), ""); getCc().put(new String("philw@ebi.ac.uk"), ""); setBcc(new HashMap()); //PeopleManager pm = new PeopleManager(); WebRequests wr = new WebRequests(); //List Bccs1 = wr.sciMails("sci_e_mail"); //List Bccs2 = wr.sciMails("sci_e_mail"); List Bccs = wr.sciMails("nullfield");//ListUtils.union(Bccs1,Bccs2); int BccSize = Bccs.size(); System.out.println("Size of list is: " + BccSize); //user asked to be removed,don't want to remove from database as details for email needed //Bccs1.remove("kgroden@interchange.ubc.ca"); //Bccs2.remove("kgroden@interchange.ubc.ca"); for (it = Bccs.listIterator(); it.hasNext();) { // Object[] o = (Object[]) it.next(); //System.out.println("object is:: " + o); String element = it.next().toString(); //String country = o[1].toString(); if (!Bcc.containsKey(it)) { // int index = Arrays.binarySearch(euCountriesList, country); // int index1 = Arrays.binarySearch(euCountriesList, country); // if (index >= 0 || index1 >= 0) { // System.out.println("Country OK :- " + country); System.out.println("element is: " + element); Bcc.put(element, ""); // } } } MimeMessage message = getJavaMailSender().createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); //helper.setValidateAddresses(false); helper.setReplyTo("emma@infrafrontier.eu"); helper.setFrom("emma@infrafrontier.eu"); System.out.println("BCC SIZE -- " + Bcc.size()); Iterator it1 = Bcc.keySet().iterator(); while (it1.hasNext()) { String BccAddress = (String) it1.next(); System.out.println("BccADDRESS===== " + BccAddress); if (BccAddress == null || BccAddress.trim().length() < 1 || !patternMatch(EMAIL_PATTERN, BccAddress)) { System.out .println("The Scientists Email address field appears to have no value or is incorrect"); BccSize = BccSize - 1; } else { //~~ helper.addBcc(BccAddress); } } System.out.println("CC SIZE -- " + Cc.size()); Iterator i = Cc.keySet().iterator(); while (i.hasNext()) { String CcAddress = (String) i.next(); System.out.println("ccADDRESS===== " + CcAddress); helper.addCc(CcAddress); } helper.setTo("emma@infrafrontier.eu");//info@emmanet.org //helper.setCc("webmaster.emmanet.org"); //helper.setBcc("philw@ebi.ac.uk"); helper.setText(content, true); helper.setSubject(subject); String filePath = Configuration.get("TMPFILES"); //String fileName = "PhenotypingSurveyCombinedNov2009.doc"; //String fileName2 = "EMPReSSslimpipelines-1.pdf"; //FileSystemResource file = new FileSystemResource(new File(filePath + fileName)); // FileSystemResource file2 = new FileSystemResource(new File(filePath + fileName2)); //helper.addAttachment(fileName, file); //helper.addAttachment(fileName2, file2); System.out.println(message); getJavaMailSender().send(message); try { BufferedWriter out = new BufferedWriter(new FileWriter(Configuration.get("FINALMAILCOUNT"))); out.write("FINAL BCC SIZE IS::" + BccSize); out.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println(helper.getMimeMessage()); } catch (MessagingException ex) { ex.printStackTrace(); } }
From source file:elaborate.editor.model.orm.service.UserService.java
void composeAndSendEmail(Configuration config, Emailer emailer, User user) { String from_email = config.getSetting(Configuration.FROM_EMAIL); String from_name = config.getSetting(Configuration.FROM_NAME); String to_email = user.getEmail(); String subject = "Elaborate4 Password reset"; Map<String, Object> map = Maps.newHashMap(); map.put("user", user.getUsername()); String token = RandomStringUtils.randomAlphanumeric(20); Log.info("token={}", token); tokenMap.put(user.getId(), token);/*from w w w. j av a2 s . c o m*/ map.put("url", MessageFormat.format("{0}/resetpassword?emailaddress={1}&token={2}", // config.getSetting(Configuration.WORK_URL), // user.getEmail(), // token// )); String body = FreeMarker.templateToString("email.ftl", map, getClass()); try { emailer.sendMail(from_email, from_name, to_email, subject, body); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:org.viafirma.util.SendMailUtil.java
/** * Crea un nuevo mail firmado. Adjuntandole el pkcs7. * /*from w ww. j av a 2 s . c o m*/ * @param key * Clave privada con la que se realiza el proceso de firma. * @param cert * Certificado utilizado. * @param certsAndCRLs * Camino de confianza. * @param dataPart * Cuerpo del email. * @return Mail firmado. * @throws CertStoreException * @throws SMIMEException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateParsingException */ private MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert, CertStore certsAndCRLs, MimeBodyPart dataPart) throws CertStoreException, SMIMEException, NoSuchAlgorithmException, NoSuchProviderException, CertificateParsingException { // Aadimos los tipos soportados ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.aES256_CBC); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert))); // Creamos el generador SMIMESignedGenerator generador = new SMIMESignedGenerator(); // Establecemos la clave privada y el mtodo de firma generador.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); // Aadimos el camino de confianza adjuntado en el mail. generador.addCertificatesAndCRLs(certsAndCRLs); // Generamos el mail firmado. MimeMultipart mensajeFirmado = generador.generate(dataPart, BouncyCastleProvider.PROVIDER_NAME); // multipart/mixed; boundary="----=_Part_2_29796765.1208556677256" try { String contentType = mensajeFirmado.getBodyPart(0).getContentType(); contentType = contentType.replaceAll("multipart/mixed", "multipart/alternative"); mensajeFirmado.getBodyPart(0).setHeader("Content-Type", contentType); // contentType =mensajeFirmado.getContentType(); // contentType=contentType.replaceAll("application/pkcs7-signature", // "application/x-pkcs7-signature"); // mensajeFirmado.getContentType(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mensajeFirmado; }
From source file:de.helmholtz_muenchen.ibis.utils.abstractNodes.HTExecutorNode.HTExecutorNodeModel.java
private void sendMail(String content) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", emailhost); Session session = Session.getDefaultInstance(properties); try {/*from w w w.j a v a 2 s . co m*/ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailsender)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject(HEADER); message.setText(content); Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); } }