List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:com.google.ie.web.controller.EmailController.java
/** * Send mail to the given email id with the provided text and subject. * /*w ww . j a va2s. co m*/ * @param recepientEmailId email id of the recepient * @param emailText text of the mail * @param subject subject of the mail * @throws IdeasExchangeException * @throws MessagingException * @throws AddressException */ protected void sendMail(String recepientEmailId, String emailText, String subject) throws IdeasExchangeException, AddressException, MessagingException { Properties prop = new Properties(); Session session = Session.getDefaultInstance(prop, null); Message message = new MimeMessage(session); message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId)); message.setFrom(new InternetAddress(getAdminMailId())); message.setText(emailText); message.setSubject(subject); Transport.send(message); log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject); }
From source file:se.vgregion.mobile.services.SmtpErrorReportService.java
@Override public void report(ErrorReport report) { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); try {/* w w w . jav a2 s . com*/ InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddress = new InternetAddress(to); simpleMessage.setFrom(fromAddress); simpleMessage.setRecipient(RecipientType.TO, toAddress); simpleMessage.setSubject(subject); String text = String.format(body, report.getPrinter().getName(), report.getDescription(), report.getReporter()); simpleMessage.setText(text); Transport.send(simpleMessage); } catch (MessagingException e) { throw new RuntimeException("Failed sending error report via mail", e); } }
From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java
/** Send mail in HTML format */ private boolean sendHtmlMail(MailSenderInfo mailInfo) { boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable"); if (enableMailAlert) { SaAuthenticatorInfo authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword()); }/*from www.java2 s . c o m*/ Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { Message mailMessage = new MimeMessage(sendMailSession); Address from = new InternetAddress(mailInfo.getFromAddress()); mailMessage.setFrom(from); Address[] to = new Address[mailInfo.getToAddress().split(",").length]; int i = 0; for (String e : mailInfo.getToAddress().split(",")) to[i++] = new InternetAddress(e); mailMessage.setRecipients(Message.RecipientType.TO, to); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8"); mainPart.addBodyPart(html); if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) { for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) { MimeBodyPart mbp = new MimeBodyPart(); File file = new File(entry.getValue()); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); try { mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null)); } catch (Exception e) { e.printStackTrace(); } mbp.setContentID(entry.getKey()); mbp.setHeader("Content-ID", "<image>"); mainPart.addBodyPart(mbp); } } List<File> list = mailInfo.getFileList(); if (list != null && list.size() > 0) { for (File f : list) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f.getAbsolutePath()); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(f.getName()); mainPart.addBodyPart(mbp); } list.clear(); } mailMessage.setContent(mainPart); // mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } } return false; }
From source file:org.geoserver.wps.mail.SendMail.java
/** * Send an EMail to a specified address. * /*from w w w .ja va 2 s .co m*/ * @param address the to address * @param subject the email address * @param body message to send * @throws MessagingException the messaging exception * @throws IOException Signals that an I/O exception has occurred. */ public void send(String address, String subject, String body) { try { // Session session = Session.getDefaultInstance(props, null); Session session = Session.getDefaultInstance(props, (conf.getMailSmtpAuth().equalsIgnoreCase("true") ? new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(conf.getUserName(), conf.getPassword()); } } : null)); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(conf.getFromAddress(), conf.getFromAddressname())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address)); message.setSubject(subject); message.setText(body.toString()); Transport.send(message); } catch (Exception e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } } }
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);//from ww w. j a va2s . co 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; }
From source file:com.app.mail.DefaultMailSender.java
private Message _populatePasswordResetToken(String emailAddress, String passwordResetToken, 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("Password Reset Token"); Map<String, Object> rootMap = new HashMap<>(); rootMap.put("passwordResetToken", passwordResetToken); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/password_token.vm", "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return 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")); }/*from w w w . j av a 2 s .c om*/ 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:uk.ac.ox.it.ords.api.statistics.services.impl.SendMailTLS.java
private void sendMail() { if (sendEmails) { if (username == null) { log.error("Unable to send emails due to null user"); return; }/*from w ww .j a v a 2 s. c o m*/ Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(props.get("mail.smtp.username").toString(), props.get("mail.smtp.password").toString()); } }); try { Message message = new MimeMessage(session); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject(subject); message.setText(messageText); message.setFrom(new InternetAddress("ords@it.ox.ac.uk")); Transport.send(message); if (log.isDebugEnabled()) { log.debug(String.format("Sent email to %s (name %s)", email, username)); log.debug("with content: " + messageText); } } catch (MessagingException e) { log.error("Unable to send email to " + email + " username " + username, e); } } }
From source file:com.app.mail.DefaultMailSender.java
private Message _populateEmailMessage(Map<SearchQuery, List<SearchResult>> searchQueryResultMap, String recipientEmailAddress, String unsubscribeToken, 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(recipientEmailAddress)); message.setSubject("New Search Results - " + MailUtil.getCurrentDate()); Map<String, Object> rootMap = new HashMap<>(); rootMap.put("emailAddress", recipientEmailAddress); rootMap.put("searchQueryResultMap", searchQueryResultMap); rootMap.put("unsubscribeToken", MailUtil.escapeUnsubscribeToken(unsubscribeToken)); rootMap.put("numberTool", new NumberTool()); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/email_body.vm", "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }
From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java
private void sendHTML(final String message) throws MessagingException, IOException { if (message == null || message.isEmpty()) { throw new IllegalArgumentException("message"); }//from w w w .j av a2s . c om final String host = properties.getConfigString("host"); final Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); final String port = properties.getConfigString("port", null); if (port != null) { props.setProperty("mail.smtp.port", port); } if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) { props.setProperty("mail.smtp.ssl.enable", "true"); } final Session session = Session.getInstance(props, null); // session.setDebug( true ); final javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(properties.getConfigString("from"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(properties.getConfigString("to"), false)); msg.setSubject("superpipes error message"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html"))); msg.setHeader("X-Mailer", "superpipes"); Transport t = null; try { t = session.getTransport("smtp"); final String username = properties.getConfigString("username", null); final String password = properties.getConfigString("password", null); if (username == null || password == null) { t.connect(); } else { if (port == null || port.isEmpty()) { t.connect(host, username, password); } else { t.connect(host, Integer.parseInt(port), username, password); } } t.sendMessage(msg, msg.getAllRecipients()); } finally { if (t != null) { t.close(); } } }