List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom, String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost String host = ConfigManager.getInstance().getSmtpMailhost(); String port = ConfigManager.getInstance().getSmtpMailport(); String password = ConfigManager.getInstance().getSmtpMailpassword(); String auth = ConfigManager.getInstance().getSmtpMailauth(); String sender = ConfigManager.getInstance().getSmtpMailuser(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.user", sender); properties.setProperty("mail.smtp.password", password); properties.setProperty("mail.smtp.auth", auth); properties.setProperty("mail.smtp.port", port); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. if (!StringUtils.isBlank(sender)) { try {//ww w. ja va2 s . co m message.setFrom(new InternetAddress(sender)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex); } } List<Address> addresses = new ArrayList<Address>(); String receivers = emails.getReceivers(); receivers = StringUtils.trim(receivers); for (String receiver : receivers.split(";")) { if (!StringUtils.isBlank(receiver)) { try { addresses.add(new InternetAddress(receiver)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex); } } } Address[] add = new Address[addresses.size()]; addresses.toArray(add); try { message.addRecipients(Message.RecipientType.TO, add); // Set Subject: header field message.setSubject("[Pundit Contact Form]: " + subject); // Now set the actual message message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n" + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex); } // Send message try { logger.log(Level.INFO, "Trying to send message to receivers: {0}", Arrays.toString(message.getAllRecipients())); transport = session.getTransport("smtp"); transport.connect(host, sender, password); transport.sendMessage(message, message.getAllRecipients()); logger.log(Level.INFO, "Sent messages to all receivers {0}", Arrays.toString(message.getAllRecipients())); } catch (NoSuchProviderException nspe) { logger.log(Level.SEVERE, "Cannot find smtp provider", nspe); } catch (MessagingException me) { logger.log(Level.SEVERE, "Cannot set transport layer ", me); } finally { try { transport.close(); } catch (MessagingException ex) { } catch (NullPointerException ne) { } } }
From source file:jp.mamesoft.mailsocketchat.Mail.java
public static void Send(String to, int mode) { //mode 0 = ?, 1 = ?, 2 = ?, 3 = ??, 4 = , 5 = System.out.println("???"); String from = Mailsocketchat.mail_user; String host = "smtp.gmail.com"; String port = "465"; String text = ""; String subject = ""; if (mode == 0) { text = logprint(text);/*from w ww. jav a 2 s. c o m*/ subject = " - MailSocketChat"; if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 1) { if (Mailsocketchat.subjectname) { subject = Mailsocketchat.logs.get(0).get("name"); } else { subject = "?? - MailSocketChat"; } text = logprint(text); } if (mode == 8) { text = logprint(text); subject = "?? - MailSocketChat"; } if (mode == 2) { if (!Mailsocketchat.push) { subject = "????? - MailSocketChat"; text = "???????????????????\n\n??????\n"; text = logprint(text); } else { subject = "??? - MailSocketChat"; text = "?????????????????\n(???????????)\n\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 3) { if (!Mailsocketchat.push && !Mailsocketchat.repeat) { subject = "???? - MailSocketChat"; text = "????\n\n??????\n"; text = logprint(text); } else { subject = "?????? - MailSocketChat"; text = "?????????????????\n\n"; if (Mailsocketchat.repeat) { text = text + "??????\n"; text = logprint(text); } } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 7) { if (!Mailsocketchat.repeat) { subject = "????? - MailSocketChat"; text = "?????30????????????\n\n"; if (!Mailsocketchat.push) { text = text + "??????\n"; text = logprint(text); } } else { subject = "??? - MailSocketChat"; text = "???\n\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 4) { subject = " - MailSocketChat"; int userint = Mailsocketchat.users.size(); int romint = Mailsocketchat.roms.size(); text = ": " + userint + " ROM: " + romint + "\n\n\n"; for (Integer id : Mailsocketchat.users.keySet()) { HashMap<String, String> data = Mailsocketchat.users.get(id); text = text + data.get("name") + "\n"; text = text + " (" + data.get("ip") + ")\n"; } text = text + "\n\nROM\n"; for (Integer id : Mailsocketchat.roms.keySet()) { HashMap<String, String> data = Mailsocketchat.roms.get(id); text = text + data.get("ip") + "\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 5) { subject = " - MailSocketChat"; if (Mailsocketchat.push) { text = "??: \n\n"; } else if (Mailsocketchat.repeat) { text = "??: \n\n"; } else { text = "??: ?\n\n"; } text = text + "?\n"; text = text + "?(fetch): ?????\n"; text = text + "(push): ????\n"; text = text + "(repeat): ????\n"; text = text + "(list): ???\n"; text = text + "#: ?????\n"; text = text + "#hoge: ??hoge????\n"; text = text + "(help): ?????\n\n"; text = text + "\nMailSocketChat Ver." + Mailsocketchat.version + "\n"; if (Mailsocketchat.newver) { text = text + "??????????\n"; } } if (mode == 6) { subject = "????????? - MailSocketChat"; text = text + "MailSocketChat??????????????????\n"; } // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); Session sendsession = Session.getInstance(props, new PlainAuthenticator(Mailsocketchat.mail_user, Mailsocketchat.mail_pass)); try { // create a message MimeMessage msg = new MimeMessage(sendsession); msg.setFrom(new InternetAddress(from)); InternetAddress[] sendaddress = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, sendaddress); msg.setSubject(subject); msg.setSentDate(new Date()); // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); Transport.send(msg); System.out.println("?????"); } catch (MessagingException mex) { System.out.println("??????"); } }
From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java
/** * Convenience method for creating an e-mail message from a set of message properties. * * @param session the mail Session instance to use * @param config the email configuration to use * @param recipientAddress the e-mail address of the recipient * @param subject the e-mail subject line * @param message the e-mail message body * * @return a Message instance//w w w .ja va 2s. co m * * @since hobson-hub-api 0.1.6 */ protected Message createMessage(Session session, EmailConfiguration config, String recipientAddress, String subject, String message) { if (config.getSenderAddress() == null) { throw new HobsonInvalidRequestException("No sender address specified; unable to execute e-mail action"); } else if (recipientAddress == null) { throw new HobsonInvalidRequestException( "No recipient address specified; unable to execute e-mail action"); } else if (subject == null) { throw new HobsonInvalidRequestException("No subject specified; unable to execute e-mail action"); } else if (message == null) { throw new HobsonInvalidRequestException("No message body specified; unable to execute e-mail action"); } try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getSenderAddress())); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress)); msg.setSubject(subject); msg.setText(message); return msg; } catch (MessagingException e) { throw new HobsonInvalidRequestException("Unable to create mail message", e); } }
From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java
@Test public void testNullPassword() throws MessagingException, EncryptorException { HasValidPassword matcher = new HasValidPassword(); MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext); matcher.init(matcherConfig);/*from w ww . ja v a2 s .c om*/ Mail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test", "text/plain"); message.setFrom(new InternetAddress("123456@example.com")); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("test4@example.com")); mail.setRecipients(recipients); Collection<?> result = matcher.match(mail); assertEquals(0, result.size()); }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
/** * Send email with Amazon Simple Email Service. * <p/>/*from ww w. j av a2s . c o m*/ * * Please note that the sender (ie 'from') must be a verified address (see * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)} * ). * <p/> * * Please note that the sender is a CC of the meail to ease support. * <p/> * * @param subject * @param body * @param from * @param toAddresses * @throws MessagingException * @throws AddressException */ public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair, java.security.KeyPair x509KeyPair, X509Certificate x509Certificate, SigningCertificate signingCertificate, String from, String toAddress) { try { Session s = Session.getInstance(new Properties(), null); MimeMessage msg = new MimeMessage(s); msg.setFrom(new InternetAddress(from)); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from)); msg.setSubject(subject); MimeMultipart mimeMultiPart = new MimeMultipart(); msg.setContent(mimeMultiPart); // body BodyPart plainTextBodyPart = new MimeBodyPart(); mimeMultiPart.addBodyPart(plainTextBodyPart); plainTextBodyPart.setContent(body, "text/plain"); // aws-credentials.txt / accessKey { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); StringWriter awsCredentialsStringWriter = new StringWriter(); PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter); awsCredentials .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials"); awsCredentials.println("#" + new DateTime()); awsCredentials.println(); awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey"); awsCredentials.println("accessKey=" + accessKey.getAccessKeyId()); awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey()); awsCredentials.println(); awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey"); awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId()); awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey()); awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain"); mimeMultiPart.addBodyPart(awsCredentialsBodyPart); } // private ssh key { BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt"); keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream"); mimeMultiPart.addBodyPart(keyPairBodyPart); } // x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart); } // x509 private key { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509CertificatePem = Pems.pem(x509Certificate); x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509CertificateBodyPart); } // Convert to raw message ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes())); ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage)); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:io.starter.datamodel.Sys.java
/** * // w w w .j a v a 2s .c o m * @param params * @throws Exception * * */ public static void sendEmail(String url, final User from, String toEmail, Map params, SqlSession session, CountDownLatch latch) throws Exception { final CountDownLatch ltc = latch; if (from == null) { throw new ServletException("Sys.sendEmail cannot have a null FROM User."); } String fromEmail = from.getEmail(); final String fro = fromEmail; final String to = toEmail; final Map p = params; final String u = url; final SqlSession sr = session; // TODO: check message sender/recipient validity if (!checkEmailValidity(fromEmail)) { throw new RuntimeException( fromEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // TODO: check mail server if it's a valid message if (!checkEmailValidity(toEmail)) { throw new RuntimeException( toEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // message.setSubject("Testing Email From Starter.io"); // Send the actual HTML message, as big as you like // fetch the content final String content = getText(u); new Thread(new Runnable() { @Override public void run() { // Sender's email ID needs to be mentioned // String sendAccount = "$EMAIL_USER_NAME$"; // final String username = "$EMAIL_USER_NAME$", password = // "hum0rm3"; // Assuming you are sending email from localhost // String host = "gator3083.hostgator.com"; String sendAccount = "$EMAIL_USER_NAME$"; final String username = "$EMAIL_USER_NAME$", password = "$EMAIL_USER_PASS$"; // Assuming you are sending email from localhost String host = SystemConstants.EMAIL_SERVER; // Get system properties Properties props = System.getProperties(); // Setup mail server props.setProperty("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); // Get the default 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. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sendAccount)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendAccount)); // Set Subject: header field Object o = p.get("MESSAGE_SUBJECT"); message.setSubject(o.toString()); String ctx = new String(content.toString()); // TODO: String Rep on the params ctx = stringRep(ctx, p); message.setContent(ctx, "text/html; charset=utf-8"); // message.setContent(new Multipart()); // Send message Transport.send(message); Logger.log("Sending message to:" + to + " SUCCESS"); } catch (MessagingException mex) { // mex.printStackTrace(); Logger.log("Sending message to:" + to + " FAILED"); Logger.error("Sys.sendEmail() failed to send message. Messaging Exception: " + mex.toString()); } // log the data Syslog logEntry = new Syslog(); logEntry.setDescription("OK [ email sent from: " + fro + " to: " + to + "]"); logEntry.setUserId(from.getId()); logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SEND_EMAIL); logEntry.setSourceId(from.getId()); // unknown logEntry.setSourceType(SystemConstants.TARGET_TYPE_USER); logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis())); SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession sesh = sqlSessionFactory.openSession(true); sesh.insert("io.starter.dao.SyslogMapper.insert", logEntry); sesh.commit(); if (ltc != null) ltc.countDown(); // release the latch } }).start(); }
From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java
@Test public void testRequestCertificateMultiThreaded() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig(); final RequestSenderCertificate mailet = new RequestSenderCertificate(); mailet.init(mailetConfig);/*from ww w . jav a2 s.c o m*/ final MimeMessage message1 = new MimeMessage(MailSession.getDefaultSession()); message1.setContent("test", "text/plain"); message1.setFrom(new InternetAddress("from@example.com")); final Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("to@example.com")); message1.saveChanges(); final MimeMessage message2 = new MimeMessage(MailSession.getDefaultSession()); message2.setContent("test", "text/plain"); message2.setFrom(new InternetAddress("from2@example.com")); Callable<Null> callable = new Callable<Null>() { @Override public Null call() throws Exception { MockMail mail1 = new MockMail(); mail1.setMessage(message1); mail1.setRecipients(recipients); mail1.setSender(new MailAddress("sender1@example.com")); mailet.service(mail1); MockMail mail2 = new MockMail(); mail2.setMessage(message2); mail2.setRecipients(recipients); mail2.setSender(new MailAddress("sender2@example.com")); mailet.service(mail2); return null; } }; Collection<Future<?>> futures = new LinkedList<Future<?>>(); for (int i = 0; i < 20; i++) { futures.add(executorService.submit(callable)); } for (Future<?> future : futures) { future.get(); } assertEquals(INITIAL_KEY_STORE_SIZE + 2, proxy.getKeyAndCertStoreSize()); }
From source file:contestWebsite.Registration.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap()); for (Entry<String, String[]> param : params.entrySet()) { if (!"studentData".equals(param.getKey())) { params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) }); }//from w ww . ja va 2 s . c om } String registrationType = params.get("registrationType")[0]; String account = "no"; if (params.containsKey("account")) { account = "yes"; } String email = params.containsKey("email") && params.get("email")[0].length() > 0 ? params.get("email")[0].toLowerCase().trim() : null; String schoolLevel = params.get("schoolLevel")[0]; String schoolName = params.get("schoolName")[0].trim(); String name = params.get("name")[0].trim(); String classification = params.containsKey("classification") ? params.get("classification")[0] : ""; String studentData = req.getParameter("studentData"); String password = null; String confPassword = null; UserCookie userCookie = UserCookie.getCookie(req); boolean loggedIn = userCookie != null && userCookie.authenticate(); if ((!loggedIn || !userCookie.isAdmin()) && email == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "E-Mail Address parameter ('email') must be specified"); return; } HttpSession sess = req.getSession(true); sess.setAttribute("registrationType", registrationType); sess.setAttribute("account", account); sess.setAttribute("account", account); sess.setAttribute("name", name); sess.setAttribute("classification", classification); sess.setAttribute("schoolName", schoolName); sess.setAttribute("schoolLevel", schoolLevel); sess.setAttribute("email", email); sess.setAttribute("studentData", studentData); boolean reCaptchaResponse = false; 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); reCaptchaResponse = JSONResponse.getBoolean("success"); } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) { resp.sendRedirect("/registration?captchaError=1"); } else { if (account.equals("yes")) { password = params.get("password")[0]; confPassword = params.get("confPassword")[0]; } Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly(); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) { if (users.size() != 0) { resp.sendRedirect("/registration?userError=1"); } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) { resp.sendRedirect("/registration?passwordError=1"); } else { resp.sendRedirect("/registration?updated=1"); } } else { Entity registration = new Entity("registration"); registration.setProperty("registrationType", registrationType); registration.setProperty("account", account); registration.setProperty("schoolName", schoolName); registration.setProperty("schoolLevel", schoolLevel); registration.setProperty("name", name); registration.setProperty("classification", classification); registration.setProperty("studentData", new Text(studentData)); registration.setProperty("email", email); registration.setProperty("paid", ""); registration.setProperty("timestamp", new Date()); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) contestInfo.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); if (account.equals("yes") && password != null && password.length() > 0 && email != null) { Entity user = new Entity("user"); String hash = Password.getSaltedHash(password); user.setProperty("name", name); user.setProperty("school", schoolName); user.setProperty("schoolLevel", schoolLevel); user.setProperty("user-id", email); user.setProperty("salt", hash.split("\\$")[0]); user.setProperty("hash", hash.split("\\$")[1]); datastore.put(user); } txn.commit(); sess.setAttribute("props", registration.getProperties()); if (email != null) { Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); String url = req.getRequestURL().toString(); url = url.substring(0, url.indexOf("/", 7)); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name)); msg.setSubject("Thank you for your registration!"); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("url", url); context.put("cost", cost); context.put("title", contestInfo.getProperty("title")); context.put("account", account.equals("yes")); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "registrationEmail", ((Text) contestInfo.getProperty("registrationEmail")).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("/registration?updated=1"); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);/* w ww .ja va 2 s.c o m*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Plain text Email test with attachment", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals("text/plain", message.getContentType()); org.jvnet.mock_javamail.Mailbox.clearAll(); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); verify(mockListener1, times(2)).getComponentId(); }
From source file:Model.DAO.java
public void sendEmail(int id, String status) { SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm"); Properties props = new Properties(); /** Parmetros de conexo com servidor Gmail */ props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("seuemail@gmail.com", "suasenha"); }/*w ww . j a va2 s. com*/ }); /** Ativa Debug para sesso */ try { PreparedStatement stmt = this.conn .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?"); stmt.setInt(1, id); ResultSet rs = stmt.executeQuery(); rs.next(); String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0]; String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1]; Message message = new MimeMessage(session); message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente Address[] toUser = InternetAddress //Destinatrio(s) .parse(rs.getString("email")); message.setRecipients(Message.RecipientType.TO, toUser); message.setSubject("Status Reserva");//Assunto message.setText("Email de alterao do status da resreva no dia " + date + " s " + time + " horas para " + status); /**Mtodo para enviar a mensagem criada*/ Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } }