List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address, String personal) throws UnsupportedEncodingException
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods, String audio) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();//from w ww . j a va 2 s . co m MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(imageds)); messageBodyPart.setFileName(image); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(audiods)); messageBodyPart.setFileName(audio); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
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:mitm.application.djigzo.ca.PFXMailBuilderTest.java
@Test public void testReplacePFXMissingMarker() throws Exception { byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX)); PFXMailBuilder builder = new PFXMailBuilder( IOUtils.toString(new FileInputStream("test/resources/templates/mail-pfx-no-marker.ftl")), templateBuilder);/*from w w w . j a va 2 s .c o m*/ String from = "123@test.com"; builder.setFrom(new InternetAddress(from, "test user")); builder.setPFX(pfx); builder.addProperty("test", "new value"); MimeMessage message = builder.createMessage(); assertNotNull(message); MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXMissingMarker.eml")); assertEquals("new value", message.getHeader("X-TEST", ",")); /* * Check if the PFX has really been replaced */ byte[] newPFX = getPFX(message); KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray()); assertEquals(22, keyStore.size()); }
From source file:com.youxifan.utils.EMail.java
/** * Add To Recipient/* www . j a v a 2 s.co m*/ * @param newTo Recipient's email address * @return true if valid */ public boolean setTo(String toEMail, String toName) { if (toEMail == null || toEMail.length() == 0) { m_valid = false; return m_valid; } InternetAddress ia = null; try { if (toName == null) ia = new InternetAddress(toEMail, true); else ia = new InternetAddress(toEMail, toName); } catch (Exception e) { log.error(toEMail + ": " + e.toString()); m_valid = false; return m_valid; } if (m_to == null) m_to = new ArrayList<InternetAddress>(); m_to.clear(); m_to.add(ia); return m_valid; }
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 ww.j av a2s . c o m*/ 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.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format)./*from w ww . j a v a 2s . c o m*/ * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
@Test public void testReplyInvalidFrom() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new PDFEncrypt(); String template = FileUtils.readFileToString(new File("test/resources/templates/pdf-attachment.ftl")); autoTransactDelegator.setGlobalProperty("pdfTemplate", template); autoTransactDelegator.setGlobalProperty("user.serverSecret", "123", true /* encrypt */); autoTransactDelegator.setGlobalProperty("user.pdf.replyAllowed", "true"); autoTransactDelegator.setGlobalProperty("user.pdf.replyURL", "http://127.0.0.1"); autoTransactDelegator.setProperty("m.brinkers@pobox.com", "user.pdf.replyAllowed", "true"); mailetConfig.setInitParameter("log", "starting"); mailetConfig.setInitParameter("template", "encrypted-pdf.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor"); mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor"); mailetConfig.setInitParameter("passwordMode", "multiple"); mailet.init(mailetConfig);//from ww w. j ava 2 s .co m MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); Passwords passwords = new Passwords(); PasswordContainer container = new PasswordContainer("test", "test ID"); passwords.put("m.brinkers@pobox.com", container); new DjigzoMailAttributesImpl(mail).setPasswords(passwords); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml")); message.setFrom(new InternetAddress("&*^&*^&*", false)); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("m.bRINKERs@pobox.com")); mail.setRecipients(recipients); mail.setSender(null); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testUserTemplateEncryptPDF", listener.getMessages()); assertEquals(1, listener.getMessages().size()); assertEquals("encryptedProcessor", listener.getStates().get(0)); assertEquals(1, listener.getRecipients().get(0).size()); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.bRINKERs@pobox.com"))); assertNull(listener.getSenders().get(0)); assertEquals(Mail.DEFAULT, mail.getState()); message = listener.getMessages().get(0); assertNotNull(message); MailUtils.validateMessage(message); checkEncryption(message, "test", false); }
From source file:bean.RedSocial.java
/** * /*from w w w . ja v a 2 s .c om*/ * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:com.aurel.track.admin.server.siteConfig.OutgoingEmailBL.java
/** * This routine tries to connect to the SMTP server with the current * configuration parameters in <code>siteApp</code>, the <code>TSiteBean</code> object stored * in the application context.//from w w w. j a v a2s. c om * @param siteBean * @param errors * @return the protocol of the connection attempt */ public static String testOutgoingEmail(TSiteBean siteBean, OutgoingEmailTO outgoingEmailTO, String emailTestTo, List<ControlError> errors, Locale locale) { SiteConfigBL.LOGGER.debug("Test sending email to:" + emailTestTo); SMTPMailSettings smtpMailSettings = new SMTPMailSettings(); smtpMailSettings.setReqAuth(outgoingEmailTO.isReqAuth()); smtpMailSettings.setAuthMode(outgoingEmailTO.getAuthMode()); smtpMailSettings.setHost(outgoingEmailTO.getServerName()); smtpMailSettings.setSecurity(outgoingEmailTO.getSecurityConnection()); smtpMailSettings.setPort(outgoingEmailTO.getPort()); smtpMailSettings.setUser(outgoingEmailTO.getUser()); smtpMailSettings.setPassword( outgoingEmailTO.getPassword() != null && outgoingEmailTO.getPassword().trim().length() > 0 ? outgoingEmailTO.getPassword() : siteBean.getSmtpPassWord()); smtpMailSettings.setMailEncoding(outgoingEmailTO.getMailEncoding()); InternetAddress internetAddressFrom = null; try { internetAddressFrom = new InternetAddress(outgoingEmailTO.getTrackEmail(), outgoingEmailTO.getEmailPersonalName()); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); List<String> controlPath = new LinkedList<String>(); controlPath.add(OutgoingEmailTO.JSONFIELDS.tabOutgoingEmail); controlPath.add(OutgoingEmailTO.JSONFIELDS.fsTrackEmail); controlPath.addAll(JSONUtility.getPathInHelpWrapper(OutgoingEmailTO.JSONFIELDS.trackEmail)); errors.add(new ControlError(controlPath, SiteConfigBL.getText("admin.server.config.err.invalidSMTPEmail", locale))); } InternetAddress internetAddressesTo = null; try { internetAddressesTo = new InternetAddress(emailTestTo); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); List<String> controlPath = new LinkedList<String>(); controlPath.add(OutgoingEmailTO.JSONFIELDS.tabOutgoingEmail); controlPath.add("fsSmtpTest"); controlPath.add("emailTestTo"); errors.add(new ControlError(controlPath, SiteConfigBL.getText("dmin.server.config.err.invalidSMTPEmailTest", locale))); } String subject = SiteConfigBL.getText("admin.server.config.trackEmailTestSubject", locale); String messageBody = SiteConfigBL.getText("admin.server.config.trackEmailTestBody", locale); boolean isPlain = true; MailSender mailSender = new MailSender(smtpMailSettings, internetAddressFrom, internetAddressesTo, subject, messageBody, isPlain); mailSender.setTimeout(new Integer(60000)); boolean ok = mailSender.send(); SiteConfigBL.LOGGER.debug("Test sending email ready"); if (!ok) { List<String> controlPath = new LinkedList<String>(); controlPath.add(OutgoingEmailTO.JSONFIELDS.tabOutgoingEmail); controlPath.add(OutgoingEmailTO.JSONFIELDS.fsSmtpServer); controlPath.addAll(JSONUtility.getPathInHelpWrapper(OutgoingEmailTO.JSONFIELDS.serverName)); errors.add(new ControlError(controlPath, "Can't send email")); } return ""; }
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 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; }