List of usage examples for javax.mail BodyPart getFileName
public String getFileName() throws MessagingException;
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testSMIMEAdaptMessageOverDirectLimit() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailetConfig.setInitParameter("directSizeLimit", "100"); mailet.init(mailetConfig);//from w w w . j a v a 2 s .co m MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml")); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testSMIMEAdaptMessageOverDirectLimit", mail.getMessage()); assertTrue(mail.getMessage().isMimeType("multipart/mixed")); assertFalse(mail.getMessage() == message); assertEquals("test 1,test 2", mail.getMessage().getHeader("X-Test", ",")); MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertTrue(bp.isMimeType("text/plain")); bp = mp.getBodyPart(1); assertTrue(bp.isMimeType("application/octet-stream")); assertEquals("attachment.smime", bp.getFileName()); }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testSMIMEAdaptMessage() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailet.init(mailetConfig);//w ww .jav a2 s .co m MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml")); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testSMIMEAdaptMessage", mail.getMessage()); assertTrue(mail.getMessage().isMimeType("multipart/mixed")); assertFalse(mail.getMessage() == message); MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent(); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertTrue(bp.isMimeType("text/plain")); bp = mp.getBodyPart(1); assertTrue(bp.isMimeType("application/octet-stream")); assertEquals("x-rimdevicesmime.p7m", bp.getFileName()); }
From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java
private void validateAttachmentBodyPart(BodyPart bodyPart) throws NotificationValidationException { try {//w ww . ja v a 2 s.com final String disposition = bodyPart.getDisposition(); if (StringUtils.isEmpty(disposition) || !disposition.equalsIgnoreCase(Part.ATTACHMENT)) { throw new NotificationValidationException(ERR_INVALID_ATTMNT_PART_MSG); } if (!bodyPart.isMimeType("application/xml")) { throw new NotificationValidationException(ERR_INVALID_ATTMNT_MIMETYPE_MSG); } validateAttachmentFileName(bodyPart.getFileName()); } catch (MessagingException e) { throw new NotificationValidationException(ERR_INVALID_MULTIPART_MSG, e); } }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
/** * <p>/*from ww w. j av a 2 s . co m*/ * Create an Amazon IAM account and send the details by email. * </p> * <p> * Created elements: * </p> * <ul> * <li>password to login to the management console if none exists,</li> * <li>accesskey if none is active,</li> * <li></li> * </ul> * * @param userName valid email used as userName of the created account. */ public void createUser(@Nonnull final String userName, GetGroupResult groupDescriptor, String keyPairName) throws Exception { Preconditions.checkNotNull(userName, "Given userName can NOT be null"); logger.info("Process user {}", userName); List<String> userAccountChanges = Lists.newArrayList(); Map<String, String> templatesParams = Maps.newHashMap(); templatesParams.put("awsCredentialsHome", "~/.aws"); templatesParams.put("awsCommandLinesHome", "/opt/amazon-aws"); User user; try { user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser(); } catch (NoSuchEntityException e) { logger.debug("User {} does not exist, create it", userName, e); user = iam.createUser(new CreateUserRequest(userName)).getUser(); userAccountChanges.add("Create user"); } List<BodyPart> attachments = Lists.newArrayList(); // AWS WEB MANAGEMENT CONSOLE LOGIN & PASSWORD try { LoginProfile loginProfile = iam.getLoginProfile(new GetLoginProfileRequest(user.getUserName())) .getLoginProfile(); templatesParams.put("loginUserName", loginProfile.getUserName()); templatesParams.put("loginPassword", "#your password has already been generated and sent to you#"); logger.info("Login profile already exists {}", loginProfile); } catch (NoSuchEntityException e) { // manually add a number to ensure amazon policy is respected String password = RandomStringUtils.randomAlphanumeric(10) + random.nextInt(10); LoginProfile loginProfile = iam .createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password)) .getLoginProfile(); userAccountChanges.add("Create user.login"); templatesParams.put("loginUserName", loginProfile.getUserName()); templatesParams.put("loginPassword", password); } // ADD USER TO GROUP Group group = groupDescriptor.getGroup(); List<User> groupMembers = groupDescriptor.getUsers(); boolean isUserInGroup = Iterables.any(groupMembers, new Predicate<User>() { public boolean apply(User groupMember) { return userName.equals(groupMember.getUserName()); } ; }); if (!isUserInGroup) { logger.debug("Add user {} to group {}", user, group); iam.addUserToGroup(new AddUserToGroupRequest(group.getGroupName(), user.getUserName())); groupMembers.add(user); userAccountChanges.add("Add user to group"); } // ACCESS KEY boolean activeAccessKeyExists = false; ListAccessKeysResult listAccessKeysResult = iam .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName())); for (AccessKeyMetadata accessKeyMetadata : listAccessKeysResult.getAccessKeyMetadata()) { StatusType status = StatusType.fromValue(accessKeyMetadata.getStatus()); if (StatusType.Active.equals(status)) { logger.info("Access key {} ({}) is already active, don't create another one.", accessKeyMetadata.getAccessKeyId(), accessKeyMetadata.getCreateDate()); activeAccessKeyExists = true; templatesParams.put("accessKeyId", accessKeyMetadata.getAccessKeyId()); templatesParams.put("accessKeySecretId", "#accessKey has already been generated and the secretId has been sent to you#"); break; } } if (!activeAccessKeyExists) { AccessKey accessKey = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName())) .getAccessKey(); userAccountChanges.add("Create user.accessKey"); logger.debug("Created access key {}", accessKey); templatesParams.put("accessKeyId", accessKey.getAccessKeyId()); templatesParams.put("accessKeySecretId", accessKey.getSecretAccessKey()); // email attachment: aws-credentials.txt { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); templatesParams.put("attachedCredentialsFileName", awsCredentialsBodyPart.getFileName()); String awsCredentials = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/aws-credentials.txt.ftl"); awsCredentialsBodyPart.setContent(awsCredentials, "text/plain"); attachments.add(awsCredentialsBodyPart); } } // SSH KEY PAIR if (keyPairName == null) { // If keyPairName is null, generate it from the username if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) { keyPairName = userName.substring(0, userName.indexOf("@xebia.")); } else { keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_"); } } try { List<KeyPairInfo> keyPairInfos = ec2 .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)).getKeyPairs(); KeyPairInfo keyPairInfo = Iterables.getOnlyElement(keyPairInfos); logger.info("SSH key {} already exists. Don't overwrite it.", keyPairInfo.getKeyName()); templatesParams.put("sshKeyName", keyPairInfo.getKeyName()); templatesParams.put("sshKeyFingerprint", keyPairInfo.getKeyFingerprint()); String sshKeyFileName = keyPairName + ".pem"; URL sshKeyFileURL = Thread.currentThread().getContextClassLoader().getResource(sshKeyFileName); if (sshKeyFileURL != null) { logger.info("SSH Key file {} found.", sshKeyFileName); BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyFileName); templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName()); keyPairBodyPart.setContent(Resources.toString(sshKeyFileURL, Charsets.ISO_8859_1), "application/x-x509-ca-cert"); attachments.add(keyPairBodyPart); } else { logger.info("SSH Key file {} NOT found.", sshKeyFileName); } } catch (AmazonServiceException e) { if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) { // ssh key does not exist, create it KeyPair keyPair = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName)).getKeyPair(); userAccountChanges.add("Create ssh key"); logger.info("Created ssh key {}", keyPair); templatesParams.put("sshKeyName", keyPair.getKeyName()); templatesParams.put("sshKeyFingerprint", keyPair.getKeyFingerprint()); BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(keyPair.getKeyName() + ".pem"); templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName()); keyPairBodyPart.setContent(keyPair.getKeyMaterial(), "application/x-x509-ca-cert"); attachments.add(keyPairBodyPart); } else { throw e; } } // X509 SELF SIGNED CERTIFICATE Collection<SigningCertificate> certificates = iam .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName)) .getCertificates(); // filter active certificates certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() { @Override public boolean apply(SigningCertificate signingCertificate) { return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus())); } }); if (certificates.isEmpty()) { java.security.KeyPair x509KeyPair = keyPairGenerator.generateKeyPair(); X509Certificate x509Certificate = generateSelfSignedX509Certificate(userName, x509KeyPair); String x509CertificatePem = Pems.pem(x509Certificate); UploadSigningCertificateResult uploadSigningCertificateResult = iam.uploadSigningCertificate( // new UploadSigningCertificateRequest(x509CertificatePem).withUserName(user.getUserName())); SigningCertificate signingCertificate = uploadSigningCertificateResult.getCertificate(); templatesParams.put("x509CertificateId", signingCertificate.getCertificateId()); userAccountChanges.add("Create x509 certificate"); logger.info("Created x509 certificate {}", signingCertificate); // email attachment: x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem"); templatesParams.put("attachedX509PrivateKeyFileName", x509PrivateKeyBodyPart.getFileName()); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/x-x509-ca-cert"); attachments.add(x509PrivateKeyBodyPart); } // email attachment: x509 certifiate pem { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem"); templatesParams.put("attachedX509CertificateFileName", x509CertificateBodyPart.getFileName()); x509CertificateBodyPart.setContent(x509CertificatePem, "application/x-x509-ca-cert"); attachments.add(x509CertificateBodyPart); } } else { SigningCertificate signingCertificate = Iterables.getFirst(certificates, null); logger.info("X509 certificate {} already exists", signingCertificate.getCertificateId()); templatesParams.put("x509CertificateId", signingCertificate.getCertificateId()); } sendEmail(templatesParams, attachments, userName); }
From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java
private MessageBody createBodyFromPart(EmailMessage msg, Part part, boolean treatAsAttachement) throws MessagingException, IOException, ServiceLocalException { MessageBody mb = new MessageBody(); if (part.isMimeType(TEXT_PLAIN)) { String s = (String) part.getContent(); mb.setBodyType(BodyType.Text); mb.setText(s);/*from ww w . j av a 2s. c o m*/ } else if (part.isMimeType(TEXT_STAR)) { logger.debug("mime-type is '" + part.getContentType() + "' handling as " + TEXT_HTML); String s = (String) part.getContent(); mb.setBodyType(BodyType.HTML); mb.setText(s); } else if (part.isMimeType(MULTIPART_ALTERNATIVE) && !treatAsAttachement) { logger.debug("mime-type is '" + part.getContentType() + "'"); Multipart mp = (Multipart) part.getContent(); String text = ""; for (int i = 0; i < mp.getCount(); i++) { Part p = mp.getBodyPart(i); if (p.isMimeType(TEXT_HTML)) { text += p.getContent(); } } mb.setText(text); mb.setBodyType(BodyType.HTML); if (!treatAsAttachement) createBodyFromPart(msg, part, true); } else if (part.isMimeType(MULTIPART_STAR) && !part.isMimeType(MULTIPART_ALTERNATIVE)) { logger.debug("mime-type is '" + part.getContentType() + "'"); Multipart mp = (Multipart) part.getContent(); int start = 0; if (!treatAsAttachement) { mb = createBodyFromPart(msg, mp.getBodyPart(start), false); start++; } for (int i = start; i < mp.getCount(); i++) { BodyPart lBodyPart = mp.getBodyPart(i); byte[] lContentBytes = bodyPart2ByteArray(lBodyPart); FileAttachment lNewAttachment; String lContentId = getFirstHeaderValue(lBodyPart, "Content-ID"); if (lContentId != null) { lNewAttachment = msg.getAttachments().addFileAttachment(lContentId, lContentBytes); lNewAttachment.setContentId(lContentId); lNewAttachment.setIsInline(true); logger.debug("Attached {} bytes as content {}", lContentBytes.length, lContentId); } else { String fileName = lBodyPart.getFileName(); fileName = (fileName == null ? "" + i : fileName); lNewAttachment = msg.getAttachments().addFileAttachment(fileName, lContentBytes); lNewAttachment.setIsInline(false); lNewAttachment.setContentType(lBodyPart.getContentType()); logger.debug("Attached {} bytes as file {}", lContentBytes.length, fileName); logger.debug("content type is {} ", lBodyPart.getContentType()); } lNewAttachment.setIsContactPhoto(false); } } return mb; }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder/*from w ww. j a va 2 s. c o m*/ * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
From source file:org.liveSense.service.email.EmailServiceImpl.java
/** * {@inheritDoc}//from w w w . j av a 2 s . co m */ @Override public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject, Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc, HashMap<String, Object> variables) throws Exception { boolean haveSession = false; try { if (session != null && session.isLive()) { haveSession = true; } else { session = repository.loginAdministrative(null); } if (template == null) { throw new RepositoryException("Template is null"); } String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables); if (html == null) throw new RepositoryException("Template is empty"); // create the messge. MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null); MimeMultipart rootMixedMultipart = new MimeMultipart("mixed"); mimeMessage.setContent(rootMixedMultipart); MimeMultipart nestedRelatedMultipart = new MimeMultipart("related"); MimeBodyPart relatedBodyPart = new MimeBodyPart(); relatedBodyPart.setContent(nestedRelatedMultipart); rootMixedMultipart.addBodyPart(relatedBodyPart); MimeMultipart messageBody = new MimeMultipart("alternative"); MimeBodyPart bodyPart = null; for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) { BodyPart bp = nestedRelatedMultipart.getBodyPart(i); if (bp.getFileName() == null) { bodyPart = (MimeBodyPart) bp; } } if (bodyPart == null) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); nestedRelatedMultipart.addBodyPart(mimeBodyPart); bodyPart = mimeBodyPart; } bodyPart.setContent(messageBody, "text/alternative"); // Create the plain text part of the message. MimeBodyPart plainTextPart = new MimeBodyPart(); plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding()); messageBody.addBodyPart(plainTextPart); // Create the HTML text part of the message. MimeBodyPart htmlTextPart = new MimeBodyPart(); htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8 messageBody.addBodyPart(htmlTextPart); // Check if resource have nt:file childs adds as attachment if (resource != null && resource.hasNodes()) { NodeIterator iter = resource.getNodes(); while (iter.hasNext()) { Node n = iter.nextNode(); if (n.getPrimaryNodeType().isNodeType("nt:file")) { // Part two is attachment MimeBodyPart attachmentBodyPart = new MimeBodyPart(); InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary() .getStream(); String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString(); String fileName = n.getName(); DataSource source = new StreamDataSource(fileData, fileName, mimeType); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName(fileName); attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); attachmentBodyPart.setContentID(fileName); rootMixedMultipart.addBodyPart(attachmentBodyPart); } } } prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc, variables); sendEmail(session, mimeMessage); // } finally { if (!haveSession && session != null) { if (session.hasPendingChanges()) { try { session.save(); } catch (Throwable th) { } } session.logout(); } } }