List of usage examples for javax.mail Message addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:domain.Employee.java
private String newPassword(String email) { if (email.equals("")) { throw new IllegalArgumentException("email must not be null"); }/*from ww w. j a v a 2s .co m*/ String pass = RandomStringUtils.randomAlphanumeric(8); //email the employee the password they can use to login Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String messagebody = String.format( "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n" + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration", getName(), getEmail(), pass); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName())); msg.setSubject("Your account has been activated"); msg.setText(messagebody); Transport.send(msg); } catch (MessagingException | UnsupportedEncodingException ex) { Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex); } //hash the string and set the employee's password to the hashed one. USED SHA256 System.out.println(pass); String hash = DigestUtils.sha256Hex(pass); return hash; }
From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java
/** * Performs some action on the given report * @param report the Report to process//from w ww . j a va 2s .c o m */ public void process(Report report, Properties configuration) { try { Message m = new MimeMessage(getSession()); m.setFrom(new InternetAddress(configuration.getProperty("from"))); for (String recipient : configuration.getProperty("to", "").split("\\,")) { m.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } // TODO: Make these such that they can contain report information m.setSubject(configuration.getProperty("subject")); Multipart multipart = new MimeMultipart(); MimeBodyPart contentBodyPart = new MimeBodyPart(); String content = configuration.getProperty("content", ""); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) { content += new String(report.getRenderedOutput()); } contentBodyPart.setContent(content, "text/html"); multipart.addBodyPart(contentBodyPart); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) { MimeBodyPart attachment = new MimeBodyPart(); Object output = report.getRenderedOutput(); if (report.getOutputContentType().contains("text")) { output = new String(report.getRenderedOutput(), "UTF-8"); } attachment.setDataHandler(new DataHandler(output, report.getOutputContentType())); attachment.setFileName(configuration.getProperty("attachmentName")); multipart.addBodyPart(attachment); } m.setContent(multipart); Transport.send(m); } catch (Exception e) { throw new RuntimeException("Error occurred while sending report over email", e); } }
From source file:org.apache.oodt.cas.crawl.action.EmailNotification.java
@Override public boolean performAction(File product, Metadata metadata) throws CrawlerActionException { try {/*from www . ja va 2 s . c o m*/ Properties props = new Properties(); props.put("mail.host", this.mailHost); props.put("mail.transport.protocol", "smtp"); props.put("mail.from", this.sender); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); msg.setSubject(PathUtils.doDynamicReplacement(subject, metadata)); msg.setText(new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); for (String recipient : recipients) { try { msg.addRecipient(Message.RecipientType.TO, new InternetAddress( PathUtils.replaceEnvVariables(recipient.trim(), metadata), ignoreInvalidAddresses)); LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); } catch (AddressException ae) { LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); LOG.warning(ae.getMessage()); } } LOG.fine("Subject: " + msg.getSubject()); LOG.fine("Message: " + new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); Transport.send(msg); return true; } catch (Exception e) { LOG.severe(e.getMessage()); 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"); }/*from w ww .j a v a 2s .com*/ 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.sfs.ucm.service.MailService.java
/** * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager. * /*from w w w . j ava 2s.co m*/ * @param fromAddress * @param ccRe * @param toRecipient * @param subject * @param body * @param messageType * - text/plain or text/html * @return status message * @throws IllegalArgumentException */ @Asynchronous public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient, final String subject, final String body, final String messageType) throws IllegalArgumentException { // argument validation if (fromAddress == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress"); } if (toRecipient == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient"); } if (subject == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined subject"); } if (body == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent"); } if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) { throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType"); } String status = null; try { Properties props = new Properties(); props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host")); props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port")); Object[] params = new Object[4]; params[0] = (String) subject; params[1] = (String) fromAddress; params[2] = (String) ccRecipient; params[3] = (String) toRecipient; logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params); Session session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); Address toAddress = new InternetAddress(toRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); if (StringUtils.isNotBlank(ccRecipient)) { Address ccAddress = new InternetAddress(ccRecipient); message.addRecipient(Message.RecipientType.CC, ccAddress); } message.setSubject(subject); message.setContent(body, messageType); Transport.send(message); } catch (AddressException e) { logger.error("sendMessage Address Exception occurred: {}", e.getMessage()); status = "sendMessage Address Exception occurred"; } catch (MessagingException e) { logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage()); status = "sendMessage Messaging Exception occurred"; } return new AsyncResult<String>(status); }
From source file:ste.xtest.mail.BugFreeFileTransport.java
@Test public void send_multipart_message() throws Exception { Session session = Session.getInstance(config); Message message = new MimeMessage(Session.getInstance(config)); message.setFrom(new InternetAddress("from@domain.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com")); message.setSubject("the subject"); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>hello world</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("src/test/resources/images/6096.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);//from w w w . ja v a 2 s . com session.getTransport().sendMessage(message, message.getAllRecipients()); then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r") .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world") .contains("Content-ID: <image>"); }
From source file:com.meg7.emailer.EmailerManager.java
private Message createMessage(List<String> emails, String fromEmail, String fromName, String subject, String text, Session session) throws MessagingException, UnsupportedEncodingException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromEmail, fromName)); for (String email : emails) { message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email, email)); }/* w w w. j av a 2 s . co m*/ message.setSubject(subject); message.setText(text); return message; }
From source file:com.assetmanager.service.mail.MailService.java
/** * Sends the activation e-mail to the given user. * * @param user the user/*from ww w . j a va2s . c om*/ * @param locale the locale * @throws MessagingException messaging exception */ public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException { final Properties props = new Properties(); final Session session = Session.getDefaultInstance(props, null); final Message message = new MimeMessage(session); final Multipart multipart = new MimeMultipart(); final MimeBodyPart htmlPart = new MimeBodyPart(); final MimeBodyPart textPart = new MimeBodyPart(); message.setFrom(new InternetAddress(getFromAddress())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale))); textPart.setContent(messageSource.getMessage("mail.body.txt", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain"); htmlPart.setContent(messageSource.getMessage("mail.body.html", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html"); multipart.addBodyPart(textPart); multipart.addBodyPart(htmlPart); message.setContent(multipart); Transport.send(message); }
From source file:contestWebsite.ContactUs.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("user") .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name"))); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3)); Entity feedback = new Entity("feedback"); if (users.size() != 0) { feedback.setProperty("user-id", users.get(0).getProperty("user-id")); }// ww w . j av a 2 s . com String name = escapeHtml4(req.getParameter("name")); String school = escapeHtml4(req.getParameter("school")); String comment = escapeHtml4(req.getParameter("text")); String email = escapeHtml4(req.getParameter("email")); HttpSession sess = req.getSession(true); sess.setAttribute("name", name); sess.setAttribute("school", school); sess.setAttribute("email", email); sess.setAttribute("comment", comment); Entity contestInfo = Retrieve.contestInfo(); if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); if (!JSONResponse.getBoolean("success")) { resp.sendRedirect("/contactUs?captchaError=1"); return; } } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } feedback.setProperty("name", name); feedback.setProperty("school", school); feedback.setProperty("email", email); feedback.setProperty("comment", new Text(comment)); feedback.setProperty("resolved", false); Transaction txn = datastore.beginTransaction(); try { datastore.put(feedback); txn.commit(); Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator")); msg.setSubject("Question about tournament from " + name); msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name), new InternetAddress(appEngineEmail, "Tournament Website Admin") }); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("email", email); context.put("school", school); context.put("message", comment); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "questionEmail", ((Text) contestInfo.getProperty("questionEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } resp.sendRedirect("/contactUs?updated=1"); sess.invalidate(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } }
From source file:com.app.mail.DefaultMailSender.java
private Message _populateMessage(String emailAddress, String subject, String template, Session session) throws Exception { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSubject(subject);/* www. j a v a 2s. c o m*/ Map<String, Object> rootMap = new HashMap<>(); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/" + template, "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }