javax.mail.internet.MimeMultipart类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(18.5k)|赞(0)|评价(0)|浏览(1099)

本文整理了Java中javax.mail.internet.MimeMultipart类的一些代码示例,展示了MimeMultipart类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MimeMultipart类的具体详情如下:
包路径:javax.mail.internet.MimeMultipart
类名称:MimeMultipart

MimeMultipart介绍

[英]The MimeMultipart class is an implementation of the abstract Multipart class that uses MIME conventions for the multipart data.

A MimeMultipart is obtained from a MimePart whose primary type is "multipart" (by invoking the part's getContent() method) or it can be created by a client as part of creating a new MimeMessage.

The default multipart subtype is "mixed". The other multipart subtypes, such as "alternative", "related", and so on, can be implemented as subclasses of MimeMultipart with additional methods to implement the additional semantics of that type of multipart content. The intent is that service providers, mail JavaBean writers and mail clients will write many such subclasses and their Command Beans, and will install them into the JavaBeans Activation Framework, so that any JavaMail implementation and its clients can transparently find and use these classes. Thus, a MIME multipart handler is treated just like any other type handler, thereby decoupling the process of providing multipart handlers from the JavaMail API. Lacking these additional MimeMultipart subclasses, all subtypes of MIME multipart data appear as MimeMultipart objects.

An application can directly construct a MIME multipart object of any subtype by using the MimeMultipart(String subtype) constructor. For example, to create a "multipart/alternative" object, use new MimeMultipart("alternative").

The mail.mime.multipart.ignoremissingendboundary property may be set to false to cause a MessagingException to be thrown if the multipart data does not end with the required end boundary line. If this property is set to true or not set, missing end boundaries are not considered an error and the final body part ends at the end of the data.

The mail.mime.multipart.ignoremissingboundaryparameter System property may be set to false to cause a MessagingException to be thrown if the Content-Type of the MimeMultipart does not include a boundary parameter. If this property is set to true or not set, the multipart parsing code will look for a line that looks like a bounary line and use that as the boundary separating the parts.

The mail.mime.multipart.ignoreexistingboundaryparameter System property may be set to true to cause any boundary to be ignored and instead search for a boundary line in the message as with mail.mime.multipart.ignoremissingboundaryparameter.

Normally, when writing out a MimeMultipart that contains no body parts, or when trying to parse a multipart message with no body parts, a MessagingException is thrown. The MIME spec does not allow multipart content with no body parts. The mail.mime.multipart.allowempty System property may be set to true to override this behavior. When writing out such a MimeMultipart, a single empty part will be included. When reading such a multipart, a MimeMultipart will be created with no body parts.
[中]MimeMultipart类是抽象多部分类的一个实现,它对多部分数据使用MIME约定。
MimeMultipart是从主要类型为“multipart”的mimemepart(通过调用该部件的getContent()方法)获取的,也可以由客户端在创建新的mimessage时创建。
默认的多部分子类型为“混合”。其他多部分子类型,如“alternative”、“related”等,可以通过其他方法实现为MiMemMultiPart的子类,以实现该类型多部分内容的附加语义。其目的是服务提供商、邮件JavaBean编写者和邮件客户端将编写许多这样的子类及其命令bean,并将它们安装到JavaBeans激活框架中,以便任何JavaMail实现及其客户端都可以透明地查找和使用这些类。因此,MIME多部分处理程序与任何其他类型处理程序一样处理,从而将提供多部分处理程序的过程与JavaMail API分离。由于缺少这些额外的MimeMultipart子类,MIME多部分数据的所有子类型都显示为MimeMultipart对象。
应用程序可以使用MimeMultipart(String subtype)构造函数直接构造任何子类型的MIME多部分对象。例如,要创建“多部分/可选”对象,请使用new MimeMultipart("alternative")
mail.mime.multipart.ignoremissingendboundary属性可以设置为false,以便在多部分数据未以所需的结束边界线结束时引发MessagingException。如果此属性设置为true或未设置,则缺少端点边界不会被视为错误,最终的身体部位将在数据的末尾结束。
如果MimMultipart的内容类型不包括boundary参数,则mail.mime.multipart.ignoremissingboundaryparameter系统属性可以设置为false以导致引发MessagingException。如果此属性设置为true或未设置,则多部分解析代码将查找一条看起来像边界线的线,并将其用作分隔部分的边界。
mail.mime.multipart.ignoreexistingboundaryparameter系统属性可以设置为true以导致忽略任何边界,而是像mail.mime.multipart.ignoremissingboundaryparameter一样在消息中搜索边界行。
通常,在写出不包含正文部分的MimeMultipart时,或者在尝试解析不包含正文部分的多部分消息时,会抛出MessagingException。MIME规范不允许没有主体部分的多部分内容。mail.mime.multipart.allowempty系统属性可以设置为true以覆盖此行为。当写出这样一个mimultipart时,将包含一个空部分。读取此类多部分时,将创建一个没有主体部分的MimeMultipart。

代码示例

代码示例来源:origin: blynkkk/blynk-server

@Override
public void sendHtmlWithAttachment(String to, String subj, String body, QrHolder[] attachments) throws Exception {
  MimeMessage message = new MimeMessage(session);
  message.setFrom(from);
  message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
  message.setSubject(subj, "UTF-8");
  Multipart multipart = new MimeMultipart();
  MimeBodyPart bodyMessagePart = new MimeBodyPart();
  bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);
  multipart.addBodyPart(bodyMessagePart);
  for (QrHolder qrHolder : attachments) {
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    attachmentsPart.setDataHandler(new DataHandler(new ByteArrayDataSource(qrHolder.data, "image/jpeg")));
    attachmentsPart.setFileName(qrHolder.makeQRFilename());
    multipart.addBodyPart(attachmentsPart);
  }
  message.setContent(multipart);
  try (Transport transport = session.getTransport()) {
    transport.connect(host, username, password);
    transport.sendMessage(message, message.getAllRecipients());
  }
  log.debug("Mail sent to {}. Subj: {}", to, subj);
  log.trace("Mail body: {}", body);
}

代码示例来源:origin: apache/usergrid

MimeMultipart msgContent = new MimeMultipart( "alternative" );
  MimeBodyPart plainPart = new MimeBodyPart();
  plainPart.setContent( plainText, "text/plain" );
  plainPart.setHeader( MIME_VERSION, "1.0" );
  plainPart.setHeader( CONTENT_TYPE, "text/plain; charset=iso-8859-1" );
  msgContent.addBodyPart( plainPart );
  htmlPart.setHeader( MIME_VERSION, "1.0" );
  htmlPart.setHeader( CONTENT_TYPE, "text/html; charset=iso-8859-1" );
  msgContent.addBodyPart( htmlPart );
MimeMessage msg = new MimeMessage( session );
msg.setContent( msgContent );
msg.setFrom( new InternetAddress( from ) );
msg.addRecipient( Message.RecipientType.TO, new InternetAddress( to ) );
msg.setSubject( subject );

代码示例来源:origin: voldemort/voldemort

MimeMultipart mp = new MimeMultipart(ds);
for(int i = 0; i < mp.getCount(); i++) {
  MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);
  String contentLocation = part.getHeader("Content-Location")[0];
  String base64Key = contentLocation.split("/")[2];
  ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key));
  ByteArrayDataSource nestedDS = new ByteArrayDataSource(part.getInputStream(),
                              "multipart/mixed");
  MimeMultipart valueParts = new MimeMultipart(nestedDS);
  for(int valueId = 0; valueId < valueParts.getCount(); valueId++) {
    MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId);
    String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
    int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

代码示例来源:origin: spring-projects/spring-framework

private MimeBodyPart getMainPart() throws MessagingException {
  MimeMultipart mimeMultipart = getMimeMultipart();
  MimeBodyPart bodyPart = null;
  for (int i = 0; i < mimeMultipart.getCount(); i++) {
    BodyPart bp = mimeMultipart.getBodyPart(i);
    if (bp.getFileName() == null) {
      bodyPart = (MimeBodyPart) bp;
    }
  }
  if (bodyPart == null) {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeMultipart.addBodyPart(mimeBodyPart);
    bodyPart = mimeBodyPart;
  }
  return bodyPart;
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * 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);
}

代码示例来源:origin: oblac/jodd

/**
 * Adds message data and attachments.
 *
 * @param emailWithData {@link Email} with data
 * @param msgToSet      {@link MimeMessage} to set data into.
 * @throws MessagingException if there is a failure.
 */
private void addBodyData(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
  final List<EmailMessage> messages = emailWithData.messages();
  final int totalMessages = messages.size();
  // Need to use new list since filterEmbeddedAttachments(List) removes attachments from the source List
  final List<EmailAttachment<? extends DataSource>> attachments = new ArrayList<>(emailWithData.attachments());
  if (attachments.isEmpty() && totalMessages == 1) {
    // special case: no attachments and just one content
    setContent(messages.get(0), msgToSet);
  } else {
    final MimeMultipart multipart = new MimeMultipart();
    final MimeMultipart msgMultipart = new MimeMultipart(ALTERNATIVE);
    multipart.addBodyPart(getBaseBodyPart(msgMultipart));
    for (final EmailMessage emailMessage : messages) {
      msgMultipart.addBodyPart(getBodyPart(emailMessage, attachments));
    }
    addAnyAttachments(attachments, multipart);
    msgToSet.setContent(multipart);
  }
}

代码示例来源:origin: stackoverflow.com

message.setFrom(new InternetAddress(from));
String[] emails = { recipient };
InternetAddress dests[] = new InternetAddress[emails.length];
for (int i = 0; i < emails.length; i++) {
  dests[i] = new InternetAddress(emails[i].trim().toLowerCase());
message.setRecipients(Message.RecipientType.TO, dests);
message.setSubject(subject, "UTF-8");
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html;charset=utf-8");
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new java.util.Date());

代码示例来源:origin: networknt/light-4j

Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailConfg.getUser()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
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);

代码示例来源:origin: stackoverflow.com

Multipart multipart = new MimeMultipart("mixed");
for (String str : attachment_PathList) {
  MimeBodyPart messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(str);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(source.getName());
  multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);

代码示例来源:origin: traccar/traccar

MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
message.setSubject(subject);
message.setSentDate(new Date());
  Multipart multipart = new MimeMultipart();
  BodyPart messageBodyPart = new MimeBodyPart();
  messageBodyPart.setContent(body, "text/html; charset=utf-8");
  multipart.addBodyPart(messageBodyPart);
  multipart.addBodyPart(attachment);
  message.setContent(multipart);

代码示例来源:origin: blynkkk/blynk-server

@Override
public void sendHtmlWithAttachment(String to, String subj, String body,
                  QrHolder[] attachmentData) throws Exception {
  MimeMessage message = new MimeMessage(session);
  message.setFrom(from);
  message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
  message.setSubject(subj, "UTF-8");
  Multipart multipart = new MimeMultipart();
  MimeBodyPart bodyMessagePart = new MimeBodyPart();
  bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);
  multipart.addBodyPart(bodyMessagePart);
  attachQRs(multipart, attachmentData);
  attachCSV(multipart, attachmentData);
  message.setContent(multipart);
  Transport.send(message);
  log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}

代码示例来源:origin: crashub/crash

MimeMessage message = new MimeMessage(session);
 message.setFrom(new InternetAddress(smtpFrom));
message.setRecipients(Message.RecipientType.TO, addresses);
if (subject != null) {
 message.setSubject(subject);
 Multipart multipart = new MimeMultipart();
 bodyPart = new MimeBodyPart();
 bodyPart.setContent(body, type);
 for (DataSource attachment : attachments) {
  MimeBodyPart attachmentPart = new MimeBodyPart();
  attachmentPart.setDataHandler(new DataHandler(attachment));
  attachmentPart.setFileName(attachment.getName());
  multipart.addBodyPart(attachmentPart);
 message.setContent(multipart);

代码示例来源:origin: SeanDragon/protools

MimeMessage message = new MimeMessage(session);
  Address[] addresses = new Address[toList.size()];
  for (int i = 0; i < toList.size(); i++) {
    addresses[i] = new InternetAddress(toList.get(i));
  message.setRecipients(Message.RecipientType.TO, addresses);
message.setSubject(mailSend.getSubject());
message.setSentDate(new DatePlus().toDate());
Multipart multipart = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(mailSend.getContent(), StrConst.DEFAULT_CHARSET_NAME);
multipart.addBodyPart(mbp, 0);
    mbp = new MimeBodyPart();
    mbp.setDataHandler(new DataHandler(fds));
    mbp.setFileName(filename);
    multipart.addBodyPart(mbp);

代码示例来源:origin: igniterealtime/Openfire

to = new InternetAddress(toEmail, toName, encoding);
  to = new InternetAddress(toEmail, "", encoding);
  from = new InternetAddress(fromEmail, fromName, encoding);
    java.util.Locale.US);
format.setTimeZone(JiveGlobals.getTimeZone());
message.setHeader("Date", format.format(new Date()));
message.setHeader("Content-Transfer-Encoding", "8bit");
message.setRecipient(Message.RecipientType.TO, to);
  MimeMultipart content = new MimeMultipart("alternative");
  MimeBodyPart text = new MimeBodyPart();
  text.setText(textBody, encoding);
  text.setDisposition(Part.INLINE);
  content.addBodyPart(text);
  content.addBodyPart(html);
  MimeMultipart mPart = new MimeMultipart();
  mPart.addBodyPart(bPart);
  MimeMultipart mPart = new MimeMultipart();
  mPart.addBodyPart(bPart);

代码示例来源:origin: shopizer-ecommerce/shopizer

mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
InternetAddress inetAddress = new InternetAddress();
inetAddress.setPersonal(eml);
inetAddress.setAddress(from);
mimeMessage.setFrom(inetAddress);
mimeMessage.setSubject(subject);
Multipart mp = new MimeMultipart("alternative");
BodyPart textPart = new MimeBodyPart();
freemarkerMailConfiguration.setClassForTemplateLoading(HtmlEmailSenderImpl.class, "/");
Template textTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
      "Can't generate text mail", e);
mp.addBodyPart(textPart);
Multipart htmlContent = new MimeMultipart("related");
BodyPart htmlPage = new MimeBodyPart();
freemarkerMailConfiguration.setClassForTemplateLoading(HtmlEmailSenderImpl.class, "/");
Template htmlTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
      "Can't generate HTML mail", e);
mimeMessage.setContent(mp);

代码示例来源:origin: pentaho/pentaho-kettle

Message msg = new MimeMessage( session );
  sender_address = sender_name + '<' + sender_address + '>';
MimeMultipart parts = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
parts.addBodyPart( part1 );
      files.setDataHandler( new DataHandler( fds ) );
      parts.addBodyPart( files );
      nrattachedFiles++;
      logBasic( "Added file '" + fds.getName() + "' to the mail message." );
    FileDataSource fds = new FileDataSource( masterZipfile );
    files.setDataHandler( new DataHandler( fds ) );
    parts.addBodyPart( files );
     messageBodyPart.setDataHandler( new DataHandler( fds ) );
     parts.addBodyPart( messageBodyPart );
     nrEmbeddedImages++;
     log.logBasic( "Image '" + fds.getName() + "' was embedded in message." );
 parts.setSubType( "related" );

代码示例来源:origin: kiegroup/jbpm

EmailNotificationHeader header = headers.get(lang);
Message msg = new MimeMessage(mailSession);
Set<String> toAddresses = new HashSet<String>();
for (User user : entry.getValue()) {
  if (emailAddress != null) {                        	
    if (toAddresses.add(emailAddress)) {
      msg.addRecipients( Message.RecipientType.TO, InternetAddress.parse( emailAddress, false));
  User user = TaskModelProvider.getFactory().newUser();
  ((InternalOrganizationalEntity) user).setId(header.getFrom());
  msg.setFrom( new InternetAddress(userInfo.getEmailForEntity(user)));
} else {
  msg.setFrom( new InternetAddress(mailSession.getProperty("mail.from")));
  Multipart multipart = new MimeMultipart();
  MimeBodyPart messageBodyPart = new MimeBodyPart();
  messageBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( body, "text/html" ) ) );         
  multipart.addBodyPart(messageBodyPart);
    multipart.addBodyPart(attachementBodyPart);
  msg.setDataHandler( new DataHandler( new ByteArrayDataSource( body, "text/html" ) ) );

代码示例来源:origin: 0opslab/opslabJutil

try {
  InternetAddress from = new InternetAddress(sender_username);
  message.setFrom(from);
  InternetAddress to = new InternetAddress(receiveUser);
  message.setRecipient(Message.RecipientType.TO, to);
  message.setSubject(subject);
  Multipart multipart = new MimeMultipart();
  BodyPart contentPart = new MimeBodyPart();
  contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
  multipart.addBodyPart(contentPart);
    BodyPart attachmentBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(attachment);
    attachmentBodyPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentBodyPart);

代码示例来源:origin: rakam-io/rakam

public void sendMail(List<String> toEmail, String title, String textContent, Optional<String> richText, Stream<MimeBodyPart> parts)
    throws MessagingException {
  Message msg = new MimeMessage(session);
  msg.setFrom(fromAddress);
  msg.addRecipients(MimeMessage.RecipientType.TO, toEmail.stream().map(e -> {
    try {
      return new InternetAddress(e);
    } catch (AddressException e1) {
      throw Throwables.propagate(e1);
    Multipart mp = new MimeMultipart();
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(richText.get(), "text/html");
    mp.addBodyPart(htmlPart);
    parts.forEach(part -> {
      try {
        mp.addBodyPart(part);
      } catch (MessagingException e) {
        throw Throwables.propagate(e);

代码示例来源:origin: psi-probe/psi-probe

MimeMultipart content = new MimeMultipart("related");
for (DataSource attachment : attachments) {
 MimeBodyPart attachmentPart = createAttachmentPart(attachment);
 content.addBodyPart(attachmentPart);
content.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
if (from == null) {
 message.setFrom();
} else {
 message.setFrom(new InternetAddress(from));
 to = InternetAddress.parse(defaultTo);
message.setRecipients(Message.RecipientType.TO, to);

相关文章