List of usage examples for javax.mail.internet MimeMessage getAllRecipients
@Override public Address[] getAllRecipients() throws MessagingException
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * verify email is sent for signing./* w w w. j a va2s .c om*/ * @return {@link String} The signing URL. * @throws IOException IOException * @throws MessagingException MessagingException */ private String verifyDocsignEmail() throws IOException, MessagingException { assertEquals(0, getMailSender().getMessages().size()); assertEquals(1, getMailSender().getMimeMessages().size()); MimeMessage msg = getMailSender().getMimeMessages().get(0); assertTrue(msg.getSubject().endsWith("sign this")); assertTrue(msg.getAllRecipients()[0].toString().endsWith("jacksmith@formkiq.com")); Multipart multipart = (Multipart) msg.getContent(); assertEquals(1, multipart.getCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); String s = out.toString(CHARSET_UTF8.name()); assertTrue(s.contains("John Smith")); assertTrue(s.contains("Jack Smith")); assertFalse(s.contains("${sendername}")); assertFalse(s.contains("${signername}")); assertFalse(s.contains("${doc}")); assertFalse(s.contains("${stoken}")); assertTrue(s.contains("Please review the document and sign at the link above")); out.close(); getMailSender().reset(); return findHrefUrl(s); }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * Verify Completion Email./*from ww w . ja va 2 s . c om*/ * @throws IOException IOException * @throws MessagingException MessagingException */ private void verifyCompleteEmail() throws IOException, MessagingException { assertEquals(0, getMailSender().getMessages().size()); assertEquals(1, getMailSender().getMimeMessages().size()); MimeMessage msg = getMailSender().getMimeMessages().get(0); assertEquals("Completed signing Sample WF", msg.getSubject()); assertEquals("test@formkiq.com", msg.getAllRecipients()[0].toString()); Multipart multipart = (Multipart) msg.getContent(); assertEquals(1, multipart.getCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); String s = out.toString(CHARSET_UTF8.name()); assertFalse(s.contains("${sendername}")); assertFalse(s.contains("${signername}")); assertFalse(s.contains("${doc}")); assertFalse(s.contains("${stoken}")); assertTrue(s.contains("has reviewed and signed the document")); out.close(); }
From source file:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java
/** * Test nominated user - new user/*from www . j av a 2 s. c o m*/ * * @throws Exception */ public void testNominatedInvitationNewUser() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, -1); Date startDate = calendar.getTime(); String inviteeFirstName = PERSON_FIRSTNAME; String inviteeLastName = PERSON_LASTNAME; String inviteeEmail = "123@alfrescotesting.com"; String inviteeUserName = null; Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE; String resourceName = SITE_SHORT_NAME_INVITE; String inviteeRole = SiteModel.SITE_COLLABORATOR; String serverPath = "wibble"; String acceptUrl = "froob"; String rejectUrl = "marshmallow"; this.authenticationComponent.setCurrentUser(USER_MANAGER); NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName, inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl, rejectUrl); assertNotNull("nominated invitation is null", nominatedInvitation); String inviteId = nominatedInvitation.getInviteId(); assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName()); assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail()); // Generated User Name should be returned inviteeUserName = nominatedInvitation.getInviteeUserName(); assertNotNull("generated user name is null", inviteeUserName); // sentInviteDate should be set to today { Date sentDate = nominatedInvitation.getSentInviteDate(); assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate, sentDate.after(startDate)); assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate, sentDate.before(new Date(new Date().getTime() + 1))); } assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType()); assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName()); assertEquals("role name wrong", inviteeRole, nominatedInvitation.getRoleName()); assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath()); assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl()); assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl()); /** * Now we have an invitation get it and check the details have been * returned correctly. */ { NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId); assertNotNull("invitation is null", invitation); assertEquals("invite id wrong", inviteId, invitation.getInviteId()); assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName()); assertEquals("resource type name wrong", resourceType, invitation.getResourceType()); assertEquals("resource name wrong", resourceName, invitation.getResourceName()); assertEquals("role name wrong", inviteeRole, invitation.getRoleName()); assertEquals("server path wrong", serverPath, invitation.getServerPath()); assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl()); assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl()); Date sentDate = invitation.getSentInviteDate(); // sentInviteDate should be set to today assertTrue("sentDate wrong too early", sentDate.after(startDate)); assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1))); } /** * Check the email itself, and check it * is as we would expect it to be */ { MimeMessage msg = mailService.retrieveLastTestMessage(); assertEquals(1, msg.getAllRecipients().length); assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString()); assertEquals(1, msg.getFrom().length); assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString()); // Hasn't been sent, so no sent or received date assertNull("Not been sent yet", msg.getSentDate()); assertNull("Not been sent yet", msg.getReceivedDate()); // TODO - check some more details of the email assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1)); } /** * Search for the new invitation */ List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType, resourceName); assertTrue("invitations is empty", !invitations.isEmpty()); NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0); assertEquals("invite id wrong", inviteId, firstInvite.getInviteId()); assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName()); /** * Now accept the invitation */ NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService .accept(firstInvite.getInviteId(), firstInvite.getTicket()); assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId()); assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName()); assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName()); List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName); assertTrue("invitations is not empty", it4.isEmpty()); /** * Now get the invitation that we accepted */ NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService .getInvitation(firstInvite.getInviteId()); assertNotNull("get after accept does not return", acceptedInvitation2); /** * Now verify access control list */ String roleName = siteService.getMembersRole(resourceName, inviteeUserName); assertEquals("role name wrong", roleName, inviteeRole); siteService.removeMembership(resourceName, inviteeUserName); /** * Check that system generated invitations can work as well */ { Field faf = mailService.getClass().getDeclaredField("fromAddress"); faf.setAccessible(true); String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService); AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL); // Check invitiation NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName, inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl, rejectUrl); assertNotNull("nominated invitation is null", nominatedInvitation2); inviteId = nominatedInvitation.getInviteId(); assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName()); assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName()); assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail()); // Check the email MimeMessage msg = mailService.retrieveLastTestMessage(); assertEquals(1, msg.getAllRecipients().length); assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString()); assertEquals(1, msg.getFrom().length); assertEquals(defaultFromAddress, msg.getFrom()[0].toString()); } }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*ww w . j a v a 2s. c o m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Hospital Organization"); mimeMessage.setText(message); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (MessagingException me) { } }
From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final ComponentLog logger = getLogger(); final List<FlowFile> invalidFlowFilesList = new ArrayList<>(); final List<FlowFile> processedFlowFilesList = new ArrayList<>(); final FlowFile originalFlowFile = session.get(); if (originalFlowFile == null) { return;// w w w . jav a 2 s. c o m } final List<String> capturedHeadersList = Arrays .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":")); final Map<String, String> attributes = new HashMap<>(); session.read(originalFlowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { Properties props = new Properties(); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage originalMessage = new MimeMessage(mailSession, in); MimeMessageParser parser = new MimeMessageParser(originalMessage).parse(); // RFC-2822 determines that a message must have a "From:" header // if a message lacks the field, it is flagged as invalid Address[] from = originalMessage.getFrom(); Date sentDate = originalMessage.getSentDate(); if (from == null || sentDate == null) { // Throws MessageException due to lack of minimum required headers throw new MessagingException("Message failed RFC2822 validation"); } else if (capturedHeadersList.size() > 0) { Enumeration headers = originalMessage.getAllHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); if (StringUtils.isNotEmpty(header.getValue()) && capturedHeadersList.contains(header.getName().toLowerCase())) { attributes.put("email.headers." + header.getName().toLowerCase(), header.getValue()); } } } if (Array.getLength(originalMessage.getAllRecipients()) > 0) { for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) { attributes.put(EMAIL_HEADER_TO + "." + toCount, originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) { attributes.put(EMAIL_HEADER_BCC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) { attributes.put(EMAIL_HEADER_CC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString()); } } // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) { attributes.put(EMAIL_HEADER_FROM + "." + toCount, originalMessage.getFrom()[toCount].toString()); } if (StringUtils.isNotEmpty(originalMessage.getMessageID())) { attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID()); } if (originalMessage.getReceivedDate() != null) { attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString()); } if (originalMessage.getSentDate() != null) { attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString()); } if (StringUtils.isNotEmpty(originalMessage.getSubject())) { attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject()); } // Zeroes EMAIL_ATTACHMENT_COUNT attributes.put(EMAIL_ATTACHMENT_COUNT, "0"); // But insert correct value if attachments are present if (parser.hasAttachments()) { attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size())); } } catch (Exception e) { // Message is invalid or triggered an error during parsing attributes.clear(); logger.error("Could not parse the flowfile {} as an email, treating as failure", new Object[] { originalFlowFile, e }); invalidFlowFilesList.add(originalFlowFile); } } }); if (attributes.size() > 0) { FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes); logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile }); processedFlowFilesList.add(updatedFlowFile); } session.transfer(processedFlowFilesList, REL_SUCCESS); session.transfer(invalidFlowFilesList, REL_FAILURE); }
From source file:org.projectforge.mail.SendMail.java
private void sendIt(final Mail composedMessage) { final Session session = Session.getInstance(properties); Transport transport = null;// w ww.j a v a2 s . c o m try { MimeMessage message = new MimeMessage(session); if (composedMessage.getFrom() != null) { message.setFrom(new InternetAddress(composedMessage.getFrom())); } else { message.setFrom(); } message.setRecipients(Message.RecipientType.TO, composedMessage.getTo()); String subject; subject = composedMessage.getSubject(); /* * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) { * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); } */ message.setSubject(subject, sendMailConfig.getCharset()); message.setSentDate(new Date()); if (composedMessage.getContentType() != null) { message.setText(composedMessage.getContent(), composedMessage.getCharset(), composedMessage.getContentType()); } else { message.setText(composedMessage.getContent(), sendMailConfig.getCharset()); } message.saveChanges(); // don't forget this transport = session.getTransport(); if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) { transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } } } log.info("E-Mail successfully sent: " + composedMessage.toString()); }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {/* w w w . j a va 2 s . co m*/ Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }
From source file:org.apache.axis2.transport.mail.server.MailSorter.java
public void processMail(ConfigurationContext confContext, MimeMessage mimeMessage) { // create an Axis server AxisEngine engine = new AxisEngine(confContext); MessageContext msgContext = null; // create and initialize a message context try {/* w w w . j a v a 2 s . c o m*/ msgContext = confContext.createMessageContext(); msgContext.setTransportIn( confContext.getAxisConfiguration().getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL)); msgContext.setTransportOut( confContext.getAxisConfiguration().getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL)); msgContext.setServerSide(true); msgContext.setProperty(Constants.CONTENT_TYPE, mimeMessage.getContentType()); msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, mimeMessage.getEncoding()); String soapAction = getMailHeader(Constants.HEADER_SOAP_ACTION, mimeMessage); if (soapAction == null) { soapAction = mimeMessage.getSubject(); } msgContext.setSoapAction(soapAction); msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL); String serviceURL = mimeMessage.getSubject(); if (serviceURL == null) { serviceURL = ""; } String replyTo = ((InternetAddress) mimeMessage.getReplyTo()[0]).getAddress(); if (replyTo != null) { msgContext.setReplyTo(new EndpointReference(replyTo)); } String recepainets = ((InternetAddress) mimeMessage.getAllRecipients()[0]).getAddress(); if (recepainets != null) { msgContext.setTo(new EndpointReference(recepainets + "/" + serviceURL)); } // add the SOAPEnvelope String message = mimeMessage.getContent().toString(); log.info("message[" + message + "]"); ByteArrayInputStream bais = new ByteArrayInputStream(message.getBytes()); String soapNamespaceURI = ""; if (mimeMessage.getContentType().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { soapNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI; } else if (mimeMessage.getContentType().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) { soapNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI; } StAXBuilder builder = BuilderUtil.getSOAPBuilder(bais, soapNamespaceURI); SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement(); msgContext.setEnvelope(envelope); AxisEngine.receive(msgContext); } catch (Exception e) { try { if (msgContext != null) { MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e); engine.sendFault(faultContext); } } catch (Exception e1) { log.error(e.getMessage(), e); } } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*from ww w. j av a2s.c om*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException { Transport t = null;/*from ww w . j a v a 2s. co m*/ try { MimeMessage message = new MimeMessage(session); t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { for (InputStream attachment : attachments.keySet()) { messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val } } catch (IOException e) { throw new MessagingException("cannot add an attachment to mail", e); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); } finally { if (t != null) { t.close(); } } }