List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2, String grupSephora, String subject, String filename) throws FileNotFoundException, IOException { Properties props = new Properties(); 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"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); }/*from ww w .java 2s.c o m*/ }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); //send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.silverpeas.core.mail.TestSmtpMailSending.java
@Test public void sendingMailSynchronouslyValidMailWithReplyTo() throws Exception { MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name"); MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name"); String subject = "A subject"; Multipart content = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE); content.addBodyPart(mimeBodyPart);//from ww w . j av a2s.com MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject) .withContent(content).setReplyToRequired(); // Sending mail mailSending.sendSynchronously(); // Verifying sent data MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend; assertThat(mailToSend.getFrom(), is(senderEmail)); assertThat(mailToSend.getTo(), hasItem(receiverEmail)); assertThat(mailToSend.getSubject(), is(subject)); assertThat(mailToSend.getContent().isHtml(), is(true)); assertThat(mailToSend.getContent().toString(), is(content.toString())); assertThat(mailToSend.isReplyToRequired(), is(true)); assertThat(mailToSend.isAsynchronous(), is(false)); assertMailSent(mailToSend); }
From source file:net.wastl.webmail.plugins.SendMessage.java
public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException, ServletException { if (sess1 == null) { throw new WebMailException( "No session was given. If you feel this is incorrect, please contact your system administrator"); }/*from w w w.ja va 2 s .c o m*/ WebMailSession session = (WebMailSession) sess1; UserData user = session.getUser(); HTMLDocument content; Locale locale = user.getPreferredLocale(); /* Save message in case there is an error */ session.storeMessage(head); if (head.isContentSet("SEND")) { /* The form was submitted, now we will send it ... */ try { MimeMessage msg = new MimeMessage(mailsession); Address from[] = new Address[1]; try { /** * Why we need * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()? * * Because we specify client browser's encoding to UTF-8, IE seems * to send all data encoded in UTF-8. We have to transcode all byte * sequences we received to UTF-8, and next we encode those strings * using MimeUtility.encodeText() depending on user's locale. Since * MimeUtility.encodeText() is used to convert the strings into its * transmission format, finally we can use the strings in the * outgoing e-mail which relies on receiver's email agent to decode * the strings. * * As described in JavaMail document, MimeUtility.encodeText() conforms * to RFC2047 and as a result, we'll get strings like "=?Big5?B......". */ /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()), // MimeUtility.encodeText(session.getUser().getFullName())); from[0] = new InternetAddress( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale), TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null, locale)); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName()); } StringTokenizer t; try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("TO").trim(), ",;"); } /* Check To: field, when empty, throw an exception */ if (t.countTokens() < 1) { throw new MessagingException("The recipient field must not be empty!"); } Address to[] = new Address[t.countTokens()]; int i = 0; while (t.hasMoreTokens()) { to[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("CC").trim(), ",;"); } Address cc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { cc[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("BCC").trim(), ",;"); } Address bcc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { bcc[i] = new InternetAddress(t.nextToken().trim()); i++; } session.setSent(false); msg.addFrom(from); if (to.length > 0) { msg.addRecipients(Message.RecipientType.TO, to); } if (cc.length > 0) { msg.addRecipients(Message.RecipientType.CC, cc); } if (bcc.length > 0) { msg.addRecipients(Message.RecipientType.BCC, bcc); } msg.addHeader("X-Mailer", WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion()); String subject = null; if (!head.isContentSet("SUBJECT")) { subject = "no subject"; } else { try { // subject=MimeUtility.encodeText(head.getContent("SUBJECT")); subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1", locale); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); subject = head.getContent("SUBJECT"); } } msg.addHeader("Subject", subject); if (head.isContentSet("REPLY-TO")) { // msg.addHeader("Reply-To",head.getContent("REPLY-TO")); msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"), "ISO8859_1", locale)); } msg.setSentDate(new Date(System.currentTimeMillis())); String contnt = head.getContent("BODY"); //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); String charset = "utf-8"; MimeMultipart cont = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); // Transcode to UTF-8 contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8"); // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { txt.setText(contnt, "Big5"); txt.setHeader("Content-Type", "text/plain; charset=\"Big5\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } else { txt.setText(contnt, "utf-8"); txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } /* Add an advertisement if the administrator requested to do so */ cont.addBodyPart(txt); if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) { MimeBodyPart adv = new MimeBodyPart(); String file = ""; if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) { file = store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } else { file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator") + store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } String advcont = ""; try { BufferedReader fin = new BufferedReader(new FileReader(file)); String line = fin.readLine(); while (line != null && !line.equals("")) { advcont += line + "\n"; line = fin.readLine(); } fin.close(); } catch (IOException ex) { } /** * Transcode to UTF-8; Since advcont comes from file, we transcode * it from default encoding. */ // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { advcont = new String(advcont.getBytes(), "Big5"); adv.setText(advcont, "Big5"); adv.setHeader("Content-Type", "text/plain; charset=\"Big5\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } else { advcont = new String(advcont.getBytes(), "UTF-8"); adv.setText(advcont, "utf-8"); adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } cont.addBodyPart(adv); } for (String attachmentKey : session.getAttachments().keySet()) { ByteStore bs = session.getAttachment(attachmentKey); InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Transfer-Encoding", "BASE64"); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); /* This is used to write to the Pipe asynchronously to avoid blocking */ StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000); BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64")); encoder.write(bs.getBytes()); encoder.flush(); encoder.close(); //MimeBodyPart att1=sconn.getResult(); MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes()); if (bs.getDescription() != "") { att1.setDescription(bs.getDescription(), "utf-8"); } /** * As described in FileAttacher.java line #95, now we need to * encode the attachment file name. */ // att1.setFileName(bs.getName()); String fileName = bs.getName(); String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry()); String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null); if (encodedFileName.equals(fileName)) { att1.addHeader("Content-Type", bs.getContentType()); att1.setFileName(fileName); } else { att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset); encodedFileName = encodedFileName.substring(localeCharset.length() + 5, encodedFileName.length() - 2); encodedFileName = encodedFileName.replace('=', '%'); att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''" + encodedFileName); } cont.addBodyPart(att1); } msg.setContent(cont); // } msg.saveChanges(); boolean savesuccess = true; msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid")); if (session.getUser().wantsSaveSent()) { String folderhash = session.getUser().getSentFolder(); try { Folder folder = session.getFolder(folderhash); Message[] m = new Message[1]; m[0] = msg; folder.appendMessages(m); } catch (MessagingException e) { savesuccess = false; } catch (NullPointerException e) { // Invalid folder: savesuccess = false; } } boolean sendsuccess = false; try { Transport.send(msg); Address sent[] = new Address[to.length + cc.length + bcc.length]; int c1 = 0; int c2 = 0; for (c1 = 0; c1 < to.length; c1++) { sent[c1] = to[c1]; } for (c2 = 0; c2 < cc.length; c2++) { sent[c1 + c2] = cc[c2]; } for (int c3 = 0; c3 < bcc.length; c3++) { sent[c1 + c2 + c3] = bcc[c3]; } sendsuccess = true; throw new SendFailedException("success", new Exception("success"), sent, null, null); } catch (SendFailedException e) { session.handleTransportException(e); } //session.clearMessage(); content = new XHTMLDocument(session.getModel(), store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme())); // if(sendsuccess) session.clearWork(); } catch (Exception e) { log.error("Could not send messsage", e); throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")"); } } else if (head.isContentSet("ATTACH")) { /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to have two targets without Javascript) */ content = parent.getURLHandler().handleURL("/compose/attach", session, head); } else { throw new DocumentNotFoundException("Could not send message. (Reason: No content given)"); } return content; }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeBodyPart????Content-Disposition: attachment * * @param file//from w w w .j a v a 2 s . co m * * @return MimeBodyPartContent-Disposition: attachment? * @throws MessagingException * @throws UnsupportedEncodingException */ private MimeBodyPart createAttachmentPart(AttachmentFile file) throws MessagingException, UnsupportedEncodingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null)); attachmentPart.setDataHandler(new DataHandler(file.getDataSource())); attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT); return attachmentPart; }
From source file:org.etudes.jforum.util.mail.Spammer.java
/** * prepare attachment message// w w w .j ava 2s.c o m * @param addresses Addresses * @param params Message params * @param subject Message subject * @param messageFile Message file * @param attachments Attachments * @throws EmailException */ protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject, String messageFile, List attachments) throws EmailException { if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments entering....."); this.message = new MimeMessage(session); try { InternetAddress[] recipients = new InternetAddress[addresses.size()]; String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET); this.message.setSentDate(new Date()); // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER))); String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; this.message.setFrom(new InternetAddress(from)); this.message.setSubject(subject, charset); this.messageText = this.getMessageText(params, messageFile); MimeBodyPart messageBodyPart = new MimeBodyPart(); String messagetype = ""; // message if (messageFormat == MESSAGE_HTML) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachments Attachment attachment = null; Iterator iterAttach = attachments.iterator(); while (iterAttach.hasNext()) { attachment = (Attachment) iterAttach.next(); // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getInfo().getRealFilename()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e); } } message.setContent(multipart); int i = 0; for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) { recipients[i] = new InternetAddress((String) iter.next()); } this.message.setRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { logger.warn(e); throw new EmailException(e); } if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments exiting....."); }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
private MimeBodyPart zipAttachment(byte[] attach, String containedFileName, String zipFileName, String nameSuffix, String fileExtension) { MimeBodyPart messageBodyPart = null; try {// w w w.ja va 2 s .c om ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(bout); String entryName = containedFileName + nameSuffix + fileExtension; zipOut.putNextEntry(new ZipEntry(entryName)); zipOut.write(attach); zipOut.closeEntry(); zipOut.close(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip"); } catch (Exception e) { // TODO: handle exception } return messageBodyPart; }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
/** * <p>//from www . j a va 2s . 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.xwiki.commons.internal.DefaultMailSender.java
private Multipart generateMimeMultipart(Mail mail) throws MessagingException { Multipart contentsMultipart = new MimeMultipart("alternative"); List<String> foundEmbeddedImages = new ArrayList<String>(); boolean hasAttachment = false; if (mail.getContents().size() == 1) // To add an alternative plain part {/*from w ww. java 2s .c om*/ String[] content = mail.getContents().get(0); if (content[0].equals("text/plain")) { BodyPart alternativePart = new MimeBodyPart(); alternativePart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING); alternativePart.setHeader("Content-Disposition", "inline"); alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable"); contentsMultipart.addBodyPart(alternativePart); } if (content[0].equals("text/html")) { BodyPart alternativePart = new MimeBodyPart(); String parsedText = createPlain(content[1]); alternativePart.setContent(parsedText, "text/plain; charset=" + EMAIL_ENCODING); alternativePart.setHeader("Content-Disposition", "inline"); alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable"); contentsMultipart.addBodyPart(alternativePart); } } for (String[] content : mail.getContents()) { BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING); contentPart.setHeader("Content-Disposition", "inline"); contentPart.setHeader("Content-Transfer-Encoding", "quoted-printable"); if (content[0].equals("text/html")) { boolean hasEmbeddedImages = false; List<MimeBodyPart> embeddedImages = new ArrayList<MimeBodyPart>(); Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher matcher = cidPattern.matcher(content[1]); String filename; while (matcher.find()) { filename = matcher.group(2); for (Attachment attachment : mail.getAttachments()) { if (filename.equals(attachment.getFilename())) { hasEmbeddedImages = true; MimeBodyPart part = createAttachmentPart(attachment); embeddedImages.add(part); foundEmbeddedImages.add(filename); } } } if (hasEmbeddedImages) { Multipart htmlMultipart = new MimeMultipart("related"); htmlMultipart.addBodyPart(contentPart); for (MimeBodyPart imagePart : embeddedImages) { htmlMultipart.addBodyPart(imagePart); } BodyPart HtmlWrapper = new MimeBodyPart(); HtmlWrapper.setContent(htmlMultipart); contentsMultipart.addBodyPart(HtmlWrapper); } else contentsMultipart.addBodyPart(contentPart); } else { contentsMultipart.addBodyPart(contentPart); } } Multipart attachmentsMultipart = new MimeMultipart(); for (Attachment attachment : mail.getAttachments()) { if (!foundEmbeddedImages.contains(attachment.getFilename())) { hasAttachment = true; MimeBodyPart part = this.createAttachmentPart(attachment); attachmentsMultipart.addBodyPart(part); } } if (hasAttachment) { Multipart wrapper = new MimeMultipart("mixed"); BodyPart body = new MimeBodyPart(); body.setContent(contentsMultipart); wrapper.addBodyPart(body); BodyPart attachments = new MimeBodyPart(); attachments.setContent(attachmentsMultipart); wrapper.addBodyPart(attachments); return wrapper; } return contentsMultipart; }
From source file:sk.lazyman.gizmo.web.app.PageEmail.java
private Multipart createHtmlPart(String html) throws IOException, MessagingException { Multipart multipart = new MimeMultipart("related"); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setDisposition(MimeMessage.INLINE); DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(html, "text/html; charset=utf-8")); bodyPart.setDataHandler(dataHandler); multipart.addBodyPart(bodyPart);//from w w w .j av a2 s .c o m return multipart; }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
protected void fillContent(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String text = getTemplate().getText(); String html = getTemplate().getHtml(); List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates(); try {//ww w .ja v a2 s .c o m if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p); // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(execution, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(execution, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(execution, multipart); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(execution, text, session); email.setText(text); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }