Java 类javax.mail.internet.MimeBodyPart 实例源码

项目:Cognizant-Intelligent-Test-Scripter    文件:Mailer.java   
private static Multipart getMessagePart() throws MessagingException, IOException {
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(getVal("msg.Body"));
    multipart.addBodyPart(messageBodyPart);
    if (getBoolVal("attach.reports")) {
        LOG.info("Attaching Reports as zip");
        multipart.addBodyPart(getReportsBodyPart());
    } else {
        if (getBoolVal("attach.standaloneHtml")) {
            multipart.addBodyPart(getStandaloneHtmlBodyPart());
        }
        if (getBoolVal("attach.console")) {
            multipart.addBodyPart(getConsoleBodyPart());
        }
        if (getBoolVal("attach.screenshots")) {
            multipart.addBodyPart(getScreenShotsBodyPart());
        }
    }
    messageBodyPart.setContent(getVal("msg.Body")
            .concat("\n\n\n")
            .concat(MailComponent.getHTMLBody()), "text/html");
    return multipart;
}
项目:JavaRushTasks    文件:Solution.java   
public static void setAttachment(Message message, String filename) throws MessagingException {
    // Create a multipar message
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();

    //Set File
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);

    //Add "file part" to multipart
    multipart.addBodyPart(messageBodyPart);

    //Set multipart to message
    message.setContent(multipart);
}
项目:LunaticSMTP    文件:ServerTest.java   
private void sendMultiPartEmail(String from, String to, String subject, String body) throws MessagingException {
    Properties props = createEmailProps(serverPort);
    Session session = Session.getInstance(props);

    Message msg = createBaseMessage(from, to, subject, session);

    MimeBodyPart p1 = new MimeBodyPart();
    p1.setText(body);

    MimeBodyPart p2 = new MimeBodyPart();
    p2.setText("Second part");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);

    msg.setContent(mp);

    Transport.send(msg);
}
项目:anti-spam-weka-gui    文件:MailHelper.java   
private static Message buildMessage(Session session, String from, String recipients, String subject, String text, String filename) throws MessagingException, AddressException
{
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
    message.setSubject(subject);

    BodyPart messageTextPart = new MimeBodyPart();
    messageTextPart.setText(text);

    BodyPart messageAttachmentPart = new MimeBodyPart();
    DataSource source = new FileDataSource(new File(filename));
    messageAttachmentPart.setDataHandler(new DataHandler(source));
    messageAttachmentPart.setFileName(filename);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageTextPart);
    multipart.addBodyPart(messageAttachmentPart);
    message.setContent(multipart);

    return message;
}
项目:camunda-bpm-mail    文件:MailTestUtil.java   
public static MimeMessage createMimeMessageWithHtml(Session session) throws MessagingException, AddressException {
  MimeMessage message = createMimeMessage(session);

  Multipart multiPart = new MimeMultipart();

  MimeBodyPart textPart = new MimeBodyPart();
  textPart.setText("text");
  multiPart.addBodyPart(textPart);

  MimeBodyPart htmlPart = new MimeBodyPart();
  htmlPart.setContent("<b>html</b>", MailContentType.TEXT_HTML.getType());
  multiPart.addBodyPart(htmlPart);

  message.setContent(multiPart);
  return message;
}
项目:ats-framework    文件:MimePackage.java   
/**
 * Add a part with the specified text to the specified position
 *
 * @param content the part's content
 * @param contentTypeSubtype the part's subtype of content type like plain (sub type of text/plain) or html (sub type of text/html)
 * @param charset the part's charset
 * @throws PackageException
 */
@PublicAtsApi
public void addPart(
                     String content,
                     String contentTypeSubtype,
                     String charset ) throws PackageException {

    // create a new inline part
    MimeBodyPart part = new MimeBodyPart();

    try {
        part.setText(content, charset, contentTypeSubtype);
        part.setDisposition(MimeBodyPart.INLINE);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }

    addPart(part, PART_POSITION_LAST);
}
项目:ats-framework    文件:MimePackage.java   
/**
 * Add the specified file as an attachment
 *
 * @param fileName
 *            name of the file
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
项目:ats-framework    文件:MimePackage.java   
/**
 * Add an attachment with the specified content - the attachment will have a
 * content type text\plain and the specified character set
 *
 * @param content
 *            the content of the attachment
 * @param charset
 *            the character set
 * @param fileName
 *            the file name for the content-disposition header
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String content,
                           String charset,
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        attPart.setText(content, charset, PART_TYPE_TEXT_PLAIN);
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(fileName);

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
项目:lams    文件:MimeMessageHelper.java   
/**
 * Set the given plain text and HTML text as alternatives, offering
 * both options to the email client. Requires multipart mode.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param plainText the plain text for the message
 * @param htmlText the HTML text for the message
 * @throws MessagingException in case of errors
 */
public void setText(String plainText, String htmlText) throws MessagingException {
    Assert.notNull(plainText, "Plain text must not be null");
    Assert.notNull(htmlText, "HTML text must not be null");

    MimeMultipart messageBody = new MimeMultipart(MULTIPART_SUBTYPE_ALTERNATIVE);
    getMainPart().setContent(messageBody, CONTENT_TYPE_ALTERNATIVE);

    // Create the plain text part of the message.
    MimeBodyPart plainTextPart = new MimeBodyPart();
    setPlainTextToMimePart(plainTextPart, plainText);
    messageBody.addBodyPart(plainTextPart);

    // Create the HTML text part of the message.
    MimeBodyPart htmlTextPart = new MimeBodyPart();
    setHtmlTextToMimePart(htmlTextPart, htmlText);
    messageBody.addBodyPart(htmlTextPart);
}
项目:unitimes    文件:JavaMailWrapper.java   
@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
       BodyPart attachment = new MimeBodyPart();
       attachment.setDataHandler(data);
       attachment.setFileName(name);
       attachment.setHeader("Content-ID", "<" + name + ">");
       iBody.addBodyPart(attachment);
}
项目:parabuild-ci    文件:Tester.java   
/**
 * Method addBodyPart
 * 
 * @param mp 
 * @param dh 
 */
private static void addBodyPart(MimeMultipart mp, DataHandler dh) {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    try {
        messageBodyPart.setDataHandler(dh);
        String contentType = dh.getContentType();
        if ((contentType == null) || (contentType.trim().length() == 0)) {
            contentType = "application/octet-stream";
        }
        System.out.println("Content type: " + contentType);
        messageBodyPart.setHeader(HEADER_CONTENT_TYPE, contentType);
        messageBodyPart.setHeader(
                HEADER_CONTENT_TRANSFER_ENCODING,
                "binary");    // Safe and fastest for anything other than mail
        mp.addBodyPart(messageBodyPart);
    } catch (javax.mail.MessagingException e) {
    }
}
项目:dswork    文件:EmailUtil.java   
public static String addAttachment(MimeMultipart mm, String path)
{
    if(count == Integer.MAX_VALUE)
    {
        count = 0;
    }
    int cid = count++;
       try
    {
        java.io.File file = new java.io.File(path);
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDisposition(MimeBodyPart.INLINE);
        mbp.setContent(new MimeMultipart("mixed"));
        mbp.setHeader("Content-ID", "<" + cid + ">");
        mbp.setDataHandler(new DataHandler(new FileDataSource(file)));
        mbp.setFileName(new String(file.getName().getBytes("GBK"), "ISO-8859-1"));
        mm.addBodyPart(mbp);
        return String.valueOf(cid);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
       return "";
}
项目:onestop-endpoints    文件:EmailPartDocumentDestination.java   
public BodyPart getBodyPart() {
    try {
        DataSource dataSource = new DataSource() {
            @Override public String getContentType() { return contentType; }
            @Override public InputStream getInputStream() { return new ByteArrayInputStream(body.toByteArray()); }
            @Override public String getName() { return filenameOrNull; }
            @Override public OutputStream getOutputStream() { throw new RuntimeException("unreachable"); }
        };

        BodyPart filePart = new MimeBodyPart();
        filePart.setDataHandler(new DataHandler(dataSource));
        if (filenameOrNull != null) {
            filePart.setFileName(filenameOrNull);
            filePart.setDisposition(Part.ATTACHMENT);
        }

        return filePart;
    }
    catch (MessagingException e) { throw new RuntimeException(e); }
}
项目:RxAndroidMail    文件:RxMailSender.java   
public synchronized void send() throws Exception {
    MimeMessage message = new MimeMessage(session);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(rxMailBuilder.getBody().getBytes(), rxMailBuilder.getType()));
    message.setFrom(new InternetAddress(rxMailBuilder.getUsername()));
    message.setSubject(rxMailBuilder.getSubject());

    message.setText(rxMailBuilder.getBody());
    message.setDataHandler(handler);
    if (_multipart.getCount() > 0) {
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(rxMailBuilder.getBody(), rxMailBuilder.getType());
        _multipart.addBodyPart(messageBodyPart);
        message.setContent(_multipart);
    }
    if (rxMailBuilder.getMailTo().indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(rxMailBuilder.getMailTo()));
    else
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(rxMailBuilder.getMailTo()));
    Transport.send(message);
}
项目:hub-email-extension    文件:MimeMultipartBuilder.java   
private MimeBodyPart buildEmailBodyPart() throws MessagingException {
    final MimeMultipart emailContent = new MimeMultipart("alternative");

    // add from low fidelity to high fidelity
    if (StringUtils.isNotBlank(text)) {
        final MimeBodyPart textBodyPart = buildTextBodyPart();
        emailContent.addBodyPart(textBodyPart);
    }

    if (StringUtils.isNotBlank(html)) {
        final MimeBodyPart htmlBodyPart = buildHtmlBodyPart();
        emailContent.addBodyPart(htmlBodyPart);
    }

    final MimeBodyPart emailBodyPart = new MimeBodyPart();
    emailBodyPart.setContent(emailContent);
    return emailBodyPart;
}
项目:carrier    文件:SMTPMessageFactory.java   
/**
 * Creates a list of {@link MimeMessage} attachments using the given incoming e-mail.
 *
 * @param email The parsed e-mail.
 * @return A list containing the attachments, if any.
 * @throws Exception If there is an error while constructing the list of attachments.
 */
private List<BodyPart> createMimeMessageAttachments(Email email) throws Exception {

    List<BodyPart> attachments = new LinkedList<>();

    for (Attachment attachment : email.getAttachments()) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setFileName(attachment.getAttachmentName());

        byte[] data = ByteStreams.toByteArray(attachment.getIs());
        DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
        attachmentBodyPart.setDataHandler(new DataHandler(source));

        attachments.add(attachmentBodyPart);
    }

    return attachments;
}
项目:spring4-understanding    文件:MimeMessageHelper.java   
/**
 * Set the given plain text and HTML text as alternatives, offering
 * both options to the email client. Requires multipart mode.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param plainText the plain text for the message
 * @param htmlText the HTML text for the message
 * @throws MessagingException in case of errors
 */
public void setText(String plainText, String htmlText) throws MessagingException {
    Assert.notNull(plainText, "Plain text must not be null");
    Assert.notNull(htmlText, "HTML text must not be null");

    MimeMultipart messageBody = new MimeMultipart(MULTIPART_SUBTYPE_ALTERNATIVE);
    getMainPart().setContent(messageBody, CONTENT_TYPE_ALTERNATIVE);

    // Create the plain text part of the message.
    MimeBodyPart plainTextPart = new MimeBodyPart();
    setPlainTextToMimePart(plainTextPart, plainText);
    messageBody.addBodyPart(plainTextPart);

    // Create the HTML text part of the message.
    MimeBodyPart htmlTextPart = new MimeBodyPart();
    setHtmlTextToMimePart(htmlTextPart, htmlText);
    messageBody.addBodyPart(htmlTextPart);
}
项目:camunda-bpm-mail    文件:MailTestUtil.java   
public static MimeMessage createMimeMessageWithAttachment(Session session, File attachment) throws MessagingException, AddressException, IOException {
  MimeMessage message = createMimeMessage(session);

  Multipart multiPart = new MimeMultipart();

  MimeBodyPart textPart = new MimeBodyPart();
  textPart.setText("text");
  multiPart.addBodyPart(textPart);

  MimeBodyPart filePart = new MimeBodyPart();
  filePart.attachFile(attachment);
  multiPart.addBodyPart(filePart);

  message.setContent(multiPart);

  return message;
}
项目:ph-as4    文件:WSS4JAttachment.java   
public void addToMimeMultipart (@Nonnull final MimeMultipart aMimeMultipart) throws MessagingException
{
  ValueEnforcer.notNull (aMimeMultipart, "MimeMultipart");

  final MimeBodyPart aMimeBodyPart = new MimeBodyPart ();

  aMimeBodyPart.setHeader (CHttpHeader.CONTENT_ID, getId ());
  // !IMPORTANT! DO NOT CHANGE the order of the adding a DH and then the last
  // headers
  // On some tests the datahandler did reset content-type and transfer
  // encoding, so this is now the correct order
  aMimeBodyPart.setDataHandler (new DataHandler (_getAsDataSource ()));

  // After DataHandler!!
  aMimeBodyPart.setHeader (CHttpHeader.CONTENT_TYPE, getMimeType ());
  aMimeBodyPart.setHeader (CHttpHeader.CONTENT_TRANSFER_ENCODING, getContentTransferEncoding ().getID ());

  aMimeMultipart.addBodyPart (aMimeBodyPart);
}
项目:communote-server    文件:MailMessageHelperTest.java   
/**
 * @param attachmentPaths
 *            Paths to attachment files.
 * @throws Exception
 *             Exception.
 * @return Message with attachments.
 */
private Message prepareMessage(String[] attachmentPaths) throws Exception {
    Message message = new MimeMessage(Session.getDefaultInstance(System.getProperties()));
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Test.");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    for (String file : attachmentPaths) {
        BodyPart attachmentPart = new MimeBodyPart();
        File attachment = new File(SRC_TEST_RESOURCES_MAILING_TEST + "/" + file);
        DataSource source = new FileDataSource(attachment);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(attachment.getName());
        multipart.addBodyPart(attachmentPart);
    }
    message.setContent(multipart);
    message.removeHeader("Content-Type");
    message.setHeader("Content-Type", "multipart/mixed");
    Assert.assertTrue(message.isMimeType("multipart/*"));
    return message;
}
项目:hermes    文件:SMimeMessage.java   
/**
 * Unsigns the encapsulated MIME body part.
 * 
 * @return the an S/MIME message encapsulating the signed content.
 * @throws SMimeException if unable to unsign the body part.
 */
public SMimeMessage unsign() throws SMimeException {
    try {
        setDefaults();

        SMIMESigned signed = new SMIMESigned((MimeMultipart)bodyPart.getContent());
        MimeBodyPart signedPart = signed.getContent();
        if (signedPart == null) {
            throw new SMimeException("No signed part");
        }
        return new SMimeMessage(signedPart, this);
    }
    catch (Exception e) {
        if (e instanceof CMSException) {
            e = ((CMSException)e).getUnderlyingException();
        }
        throw new SMimeException("Unable to unsign body part", e);
    }
}
项目:hermes    文件:SMimeMessage.java   
/**
   * Compresses the encapsulated MIME body part.
   * 
   * @return an S/MIME message encapsulating the compressed MIME body part. 
   * @throws SMimeException if unable to compress the body part.
   */
  public SMimeMessage compress() throws SMimeException {
      try {
          try {
              setDefaults();

              /* Create the generator for creating an smime/compressed body part */
              SMIMECompressedGenerator compressor = new SMIMECompressedGenerator();
              compressor.setContentTransferEncoding(getContentTransferEncoding());

              /* compress the body part */ 
              // MimeBodyPart compressedPart = compressor.generate(bodyPart, SMIMECompressedGenerator.ZLIB);
MimeBodyPart compressedPart = compressor.generate(bodyPart, new ZlibCompressor());
              return new SMimeMessage(compressedPart, this);
          }
          catch (org.bouncycastle.mail.smime.SMIMEException ex) {
              throw new SMimeException(ex.getMessage(), ex.getUnderlyingException());
          }
      }
      catch (Exception e) {
          throw new SMimeException("Unable to compress body part", e);
      }
  }
项目:hermes    文件:SFRMMessage.java   
public void decrypt(X509Certificate cert, PrivateKey privateKey) throws SFRMException {
    try {
        SMIMEEnveloped m = new SMIMEEnveloped(bodyPart);

 RecipientId recId = new JceKeyTransRecipientId(cert);

 RecipientInformationStore  recipientsInfo = m.getRecipientInfos(); 
 RecipientInformation       recipientInfo = recipientsInfo.get(recId);

        if (recipientInfo == null) {
            throw new SFRMMessageException("Invalid encrypted content");
        }

 JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(privateKey);
 recipient.setProvider(SECURITY_PROVIDER);                          

        this.bodyPart = new MimeBodyPart(new ByteArrayInputStream(recipientInfo.getContent(recipient)));
        this.setIsEncrypted(true);
    } catch (org.bouncycastle.cms.CMSException ex) {
        throw new SFRMException("Unable to decrypt body part", ex.getUnderlyingException());
    } catch (Exception e) {
        throw new SFRMException("Unable to decrypt body part", e);
    }
}
项目:Camel    文件:MimeMultipartDataFormat.java   
private String getAttachmentKey(BodyPart bp) throws MessagingException, UnsupportedEncodingException {
    // use the filename as key for the map
    String key = bp.getFileName();
    // if there is no file name we use the Content-ID header
    if (key == null && bp instanceof MimeBodyPart) {
        key = ((MimeBodyPart)bp).getContentID();
        if (key != null && key.startsWith("<") && key.length() > 2) {
            // strip <>
            key = key.substring(1, key.length() - 1);
        }
    }
    // or a generated content id
    if (key == null) {
        key = UUID.randomUUID().toString() + "@camel.apache.org";
    }
    return MimeUtility.decodeText(key);
}
项目:RxAndroidMail    文件:RxMailSender.java   
private void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    messageBodyPart.setHeader("Content-ID","<image>");

    _multipart.addBodyPart(messageBodyPart);
}
项目:alimama    文件:SimpleSendReceiveMessage.java   
/**
 * 创建复杂的正文
 * @return
 * @throws MessagingException 
 */
private Multipart createMultiPart() throws MessagingException {
    // TODO Auto-generated method stub
    Multipart multipart=new MimeMultipart();

    //第一块
    BodyPart bodyPart1=new MimeBodyPart();
    bodyPart1.setText("创建复杂的邮件,此为正文部分");
    multipart.addBodyPart(bodyPart1);

    //第二块 以附件形式存在
    MimeBodyPart bodyPart2=new MimeBodyPart();
    //设置附件的处理器
    FileDataSource attachFile=new FileDataSource(ClassLoader.getSystemResource("attach.txt").getFile());
    DataHandler dh=new DataHandler(attachFile);
    bodyPart2.setDataHandler(dh);
    bodyPart2.setDisposition(Part.ATTACHMENT);
    bodyPart2.setFileName("test");
    multipart.addBodyPart(bodyPart2);

    return multipart;
}