List of usage examples for javax.mail.internet MimeMessage setSentDate
@Override public void setSentDate(Date d) throws MessagingException
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/*from w ww . j a va 2s .co m*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VitroRequest vreq = new VitroRequest(request); String confirmpage = "/confirmUserMail.jsp"; String errpage = "/contact_err.jsp"; String status = null; // holds the error status if (!FreemarkerEmailFactory.isConfigured(vreq)) { status = "This application has not yet been configured to send mail. " + "Email properties must be specified in the configuration properties file."; response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); return;//from www . j ava2 s .c o m } String SPAM_MESSAGE = "Your message was flagged as spam."; boolean probablySpam = false; String spamReason = ""; String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer"); request.getSession().removeAttribute("commentsFormReferer"); if (originalReferer == null) { originalReferer = "none"; // (the following does not support cookie-less browsing:) // probablySpam = true; // status = SPAM_MESSAGE; } else { String referer = request.getHeader("Referer"); //Review how spam works? /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) { probablySpam=true; status = SPAM_MESSAGE ; spamReason = "The form was not submitted from the Contact Us or Corrections page."; }*/ } String formType = vreq.getParameter("DeliveryType"); List<String> deliverToArray = null; int recipientCount = 0; String deliveryfrom = null; // get Individuals that the User mayEditAs deliverToArray = getEmailsForAllUserAccounts(vreq); //Removed all form type stuff b/c recipients pre-configured recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size(); if (recipientCount == 0) { //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\""); throw new Error("To establish the Contact Us mail capability the system administrators must " + "specify at least one email address in the current portal."); } // obtain passed in form data with a simple trim on the values String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception String webuseremail = vreq.getParameter("webuseremail");//.trim(); String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify? //webusername = "hjk54"; //webuseremail = "hjk54@cornell.edu"; //comments = "following are comments"; webusername = webusername.trim(); deliveryfrom = webuseremail; comments = comments.trim(); //Removed spam filtering code StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix // from MyLibrary msgBuf.setLength(0); //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator); msgBuf.append("<html>" + lineSeparator); msgBuf.append("<head>" + lineSeparator); msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator); msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator); msgBuf.append("</head>" + lineSeparator); msgBuf.append("<body>" + lineSeparator); msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator); msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address " + request.getRemoteAddr() + "</h4>" + lineSeparator); //Don't need any 'likely viewing page' portion to be emailed out to the others msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator); if (comments == null || comments.equals("")) { msgBuf.append("<p>BLANK MESSAGE</p>"); } else { msgBuf.append("<p>" + comments + "</p>"); } msgBuf.append("</body>" + lineSeparator); msgBuf.append("</html>" + lineSeparator); String msgText = msgBuf.toString(); Calendar cal = Calendar.getInstance(); /* outFile.println("<hr/>"); outFile.println(); outFile.println("<p>"+cal.getTime()+"</p>"); outFile.println(); if (probablySpam) { outFile.println("<p>REJECTED - SPAM</p>"); outFile.println("<p>"+spamReason+"</p>"); outFile.println(); } outFile.print( msgText ); outFile.println(); outFile.println(); outFile.flush(); // outFile.close(); */ Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { // Construct the message MimeMessage msg = new MimeMessage(s); log.debug("trying to send message from servlet"); // Set the from address msg.setFrom(new InternetAddress(webuseremail)); // Set the recipient address if (recipientCount > 0) { InternetAddress[] address = new InternetAddress[recipientCount]; for (int i = 0; i < recipientCount; i++) { address[i] = new InternetAddress(deliverToArray.get(i)); } msg.setRecipients(Message.RecipientType.TO, address); } // Set the subject and text msg.setSubject(deliveryfrom); // add the multipart to the message msg.setContent(msgText, "text/html"); // set the Date: header msg.setSentDate(new Date()); log.debug("sending from servlet"); //if (!probablySpam) Transport.send(msg); // try to send the message via smtp - catch error exceptions } catch (AddressException e) { status = "Please supply a valid email address."; log.debug("Error - status is " + status); } catch (SendFailedException e) { status = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]"; log.error("Error - status is " + status); } catch (MessagingException e) { status = "The system was unable to deliver your mail. Please try again later. [MESSAGING]"; log.error("Error - status is " + status, e); } //outFile.flush(); //outFile.close(); // Redirect to the appropriate confirmation page if (status == null && !probablySpam) { // message was sent successfully response.sendRedirect("test?bodyJsp=" + confirmpage); } else { // exception occurred response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from w w w . ja v a 2 s .c om props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java
private void sendIcalMessage() throws Exception { log.debug("sendIcalMessage"); // Evaluating Configuration Data String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value(); String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value(); // String from = "openmeetings@xmlcrm.org"; String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value(); String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value(); String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value(); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", smtpPort); Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable"); if (conf != null) { if (conf.getConf_value().equals("1")) { props.put("mail.smtp.starttls.enable", "true"); }// w ww .java2s. com } // Check for Authentification Session session = null; if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null && emailUserpass.length() > 0) { // use SMTP Authentication props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass)); } else { // not use SMTP Authentication session = Session.getDefaultInstance(props, null); } // Building MimeMessage MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false)); // -- Create a new message -- BodyPart msg = new MimeBodyPart(); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\""))); Multipart multipart = new MimeMultipart(); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource( new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); multipart.addBodyPart(msg); mimeMessage.setSentDate(new Date()); mimeMessage.setContent(multipart); // -- Set some other header information -- // mimeMessage.setHeader("X-Mailer", "XML-Mail"); // mimeMessage.setSentDate(new Date()); // Transport trans = session.getTransport("smtp"); Transport.send(mimeMessage); }
From source file:org.grouter.common.mail.MailHandler.java
/** * @param mimeMessage/*w w w. ja v a 2 s . c o m*/ * @throws UnsupportedEncodingException * @throws MessagingException */ private void createHeader(MimeMessage mimeMessage, MailDto mailDto) throws UnsupportedEncodingException, MessagingException { //from InternetAddress fromAddress = new InternetAddress(mailDto.getFrom()); fromAddress.setPersonal(mailDto.getSenderNote(), ENCODING); mimeMessage.setSender(fromAddress); //to List<String> senders = mailDto.getTo(); InternetAddress[] toAddress = getRecipients(senders); List<String> sendersCc = mailDto.getCc(); InternetAddress[] toAddressCc = getRecipients(sendersCc); List<String> sendersBcc = mailDto.getBcc(); InternetAddress[] toAddressBcc = getRecipients(sendersBcc); mimeMessage.setRecipients(Message.RecipientType.TO, toAddress); mimeMessage.setRecipients(Message.RecipientType.CC, toAddressCc); mimeMessage.setRecipients(Message.RecipientType.BCC, toAddressBcc); //subject mimeMessage.setSubject(mailDto.getSubject(), ENCODING); //sent date mimeMessage.setSentDate(new Date()); }
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 www . 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:org.nuxeo.ecm.user.invite.UserInvitationComponent.java
protected void generateMail(String destination, String copy, String title, String content) throws NamingException, MessagingException { InitialContext ic = new InitialContext(); Session session = (Session) ic.lookup(getJavaMailJndiName()); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false)); if (!isBlank(copy)) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false)); }//from w w w.j av a 2s . co m msg.setSubject(title, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content, "text/html; charset=utf-8"); Transport.send(msg); }
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);/*from w ww. ja v a 2 s . c om*/ 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:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *///from w w w . j a v a 2 s. c om public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
From source file:org.overlord.sramp.governance.services.NotificationResource.java
/** * POST to email a notification about an artifact. * * @param environment/*from w ww .j a va 2 s . c o m*/ * @param uuid * @throws SrampAtomException */ @POST @Path("email/{group}/{template}/{target}/{uuid}") @Produces("application/xml") public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request, @PathParam("group") String group, @PathParam("template") String template, @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception { Map<String, ValueEntity> results = new HashMap<String, ValueEntity>(); try { // 0. run the decoder on the arguments, after replacing * by % (this so parameters can // contain slashes (%2F) group = SlashDecoder.decode(group); template = SlashDecoder.decode(template); target = SlashDecoder.decode(target); uuid = SlashDecoder.decode(uuid); // 1. get the artifact from the repo SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient(); QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$ if (queryResultSet.size() == 0) { results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$ results.put(GovernanceConstants.MESSAGE, new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$ return results; } ArtifactSummary artifactSummary = queryResultSet.iterator().next(); // 2. get the destinations for this group NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$ if (destinations == null) { destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(), group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$ } // 3. send the email notification try { MimeMessage m = new MimeMessage(mailSession); Address from = new InternetAddress(destinations.getFromAddress()); Address[] to = new InternetAddress[destinations.getToAddresses().length]; for (int i = 0; i < destinations.getToAddresses().length; i++) { to[i] = new InternetAddress(destinations.getToAddresses()[i]); } m.setFrom(from); m.setRecipients(Message.RecipientType.TO, to); String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$ URL subjectUrl = Governance.class.getClassLoader().getResource(subject); if (subjectUrl != null) subject = IOUtils.toString(subjectUrl); subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$ subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$ subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$ m.setSubject(subject); m.setSentDate(new java.util.Date()); String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$ URL contentUrl = Governance.class.getClassLoader().getResource(content); if (contentUrl != null) content = IOUtils.toString(contentUrl); content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$ content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$ content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$ content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$ m.setContent(content, "text/plain"); //$NON-NLS-1$ Transport.send(m); } catch (javax.mail.MessagingException e) { logger.error(e.getMessage(), e); } // 4. build the response results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$ return results; } catch (Exception e) { logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$ throw new SrampAtomException(e); } }