下面列出了怎么用javax.mail.internet.MimeBodyPart的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
/**
* Attaches a file as a body part to the multipart message
*
* @param attachment
* @throws MessagingException
*/
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException
{
DataSource source = attachment.getDataSource();
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(attachment.getFilename());
if (attachment.getContentTypeHeader() != null) {
attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
}
if (attachment.getContentDispositionHeader() != null) {
attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
}
return attachPart;
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
public void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
MimeMessage message = (MimeMessage) messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
private Map<String, String> getInfoFromBody(String bodyContent, String key)
throws MessagingException {
MimeBodyPart part = new MimeBodyPart(new ByteArrayInputStream(bodyContent.getBytes()));
Map<String, String> info = new HashMap<String, String>(6);
info.put("key", key);
info.put("content-type", part.getContentType());
info.put("creation-date", part.getHeader(UPLOAD_CREATION_HEADER)[0]);
info.put("filename", part.getFileName());
info.put("size", part.getHeader(CONTENT_LENGTH_HEADER)[0]); // part.getSize() returns 0
info.put("md5-hash", part.getContentMD5());
String[] headers = part.getHeader(CLOUD_STORAGE_OBJECT_HEADER);
if (headers != null && headers.length == 1) {
info.put("gs-name", headers[0]);
}
return info;
}
@Test
public void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
private static MimeBodyPart part(final ChainedHttpConfig config, final MultipartContent.MultipartPart multipartPart) throws MessagingException {
final MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setDisposition("form-data");
if (multipartPart.getFileName() != null) {
bodyPart.setFileName(multipartPart.getFileName());
bodyPart.setHeader("Content-Disposition", format("form-data; name=\"%s\"; filename=\"%s\"", multipartPart.getFieldName(), multipartPart.getFileName()));
} else {
bodyPart.setHeader("Content-Disposition", format("form-data; name=\"%s\"", multipartPart.getFieldName()));
}
bodyPart.setDataHandler(new DataHandler(new EncodedDataSource(config, multipartPart.getContentType(), multipartPart.getContent())));
bodyPart.setHeader("Content-Type", multipartPart.getContentType());
return bodyPart;
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject","testContent", true, false);
verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
MimeMessage message = (MimeMessage) messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart)((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
protected void calcAndStoreMic(Message msg, MimeBodyPart mbp, boolean includeHeaders) throws Exception {
// Calculate and get the original mic
// includeHeaders = (msg.getHistory().getItems().size() > 1);
String mdnOptions = msg.getPartnership().getAttributeOrProperty(Partnership.PA_AS2_MDN_OPTIONS, null);
if (mdnOptions == null || mdnOptions.length() < 1) {
throw new OpenAS2Exception("Partner attribute " + Partnership.PA_AS2_MDN_OPTIONS + "is required but can be set to \"none\"");
}
if ("none".equalsIgnoreCase(mdnOptions)) {
return;
}
DispositionOptions dispOptions = new DispositionOptions(mdnOptions);
msg.setCalculatedMIC(AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg(), includeHeaders, msg.getPartnership().isPreventCanonicalization()));
if (logger.isTraceEnabled()) {
// Generate some alternative MIC's to see if the partner is somehow using a
// different default
String tmic = AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg(), includeHeaders, !msg.getPartnership().isPreventCanonicalization());
logger.trace("MIC outbound with forced reversed prevent canocalization: " + tmic + msg.getLogMsgID());
tmic = AS2Util.getCryptoHelper().calculateMIC(msg.getData(), dispOptions.getMicalg(), false, msg.getPartnership().isPreventCanonicalization());
logger.trace("MIC outbound with forced exclude headers flag: " + tmic + msg.getLogMsgID());
}
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("JHipster Online <[email protected]>");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
/**
* Generate multi part / alternative message
*/
private MimeMessage generateMessage() throws MessagingException {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("Test <[email protected]>");
msg.setSubject("subject");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Body's text (text)", "UTF-8");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<p>Body's text <strong>(html)</strong></p>", "text/html; charset=UTF-8");
Multipart multiPart = new MimeMultipart("alternative");
multiPart.addBodyPart(textPart); // first
multiPart.addBodyPart(htmlPart); // second
msg.setContent(multiPart);
msg.addHeader("X-Custom-Header", "CustomValue");
return msg;
}
/**
* 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);
}
}
public MimeBodyPart compress(Message msg, MimeBodyPart mbp, String compressionType, String contentTxfrEncoding) throws SMIMEException, OpenAS2Exception {
OutputCompressor compressor = null;
if (compressionType != null) {
if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB)) {
compressor = new ZlibCompressor();
} else {
throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
}
}
SMIMECompressedGenerator sCompGen = new SMIMECompressedGenerator();
sCompGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
MimeBodyPart smime = sCompGen.generate(mbp, compressor);
if (logger.isTraceEnabled()) {
try {
logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Type:" + smime.getContentType());
logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + smime.getDisposition());
} catch (MessagingException e) {
}
}
return smime;
}
public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
ContentType contentType = new ContentType(part.getContentType());
String baseType = contentType.getBaseType().toLowerCase();
if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
String smimeType = contentType.getParameter("smime-type");
boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
if (!checkResult && logger.isDebugEnabled()) {
logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
}
return (checkResult);
}
if (logger.isDebugEnabled()) {
logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
}
return false;
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException {
MimeBodyPart part = new MimeBodyPart();
MimeMessage originalMessage = originalMail.getMessage();
if (attachmentType.equals(TypeCode.HEADS)) {
part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain");
part.setHeader("Content-Type", "text/rfc822-headers");
} else {
part.setContent(originalMessage, "message/rfc822");
}
if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) {
part.setFileName(originalMessage.getSubject().trim());
} else {
part.setFileName("No Subject");
}
part.setDisposition("Attachment");
return part;
}
private void addAttachedFilePart( FileObject file ) throws Exception {
// create a data source
MimeBodyPart files = new MimeBodyPart();
// create a data source
URLDataSource fds = new URLDataSource( file.getURL() );
// get a data Handler to manipulate this file type;
files.setDataHandler( new DataHandler( fds ) );
// include the file in the data source
files.setFileName( file.getName().getBaseName() );
// insist on base64 to preserve line endings
files.addHeader( "Content-Transfer-Encoding", "base64" );
// add the part with the file in the BodyPart();
data.parts.addBodyPart( files );
if ( isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "Mail.Log.AttachedFile", fds.getName() ) );
}
}
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;
}
/**
* 文件对象包装为邮件内容
*
* @param file 文件对象
* @return 邮件内容对象
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public static MimeBodyPart wrapFile2BodyPart(File file) throws MessagingException, UnsupportedEncodingException {
MimeBodyPart filePartBody = new MimeBodyPart();
DataSource fileDataSource = new FileDataSource(file);
DataHandler dataHandler = new DataHandler(fileDataSource);
filePartBody.setDataHandler(dataHandler);
filePartBody.setFileName(MimeUtility.encodeText(file.getName()));
return filePartBody;
}
/**
* 追加内嵌图片
* @author hf-hf
* @date 2018/12/27 16:53
* @param images
* @param multipart
* @throws MessagingException
*/
private void addImages(File[] images, MimeMultipart multipart) throws MessagingException {
if (null != images && images.length > 0) {
for (int i = 0; i < images.length; i++) {
MimeBodyPart imagePart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource(images[i]));
imagePart.setDataHandler(dataHandler);
imagePart.setContentID(images[i].getName());
multipart.addBodyPart(imagePart);
}
}
}
@Override
public void doHtmlSend(MailData mailData) throws Exception {
/**创建一个邮件的会话**/
Authenticator authenticator = null;
if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器
authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword());
}
};
}
Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator);
/**创建邮件信心**/
Message message = new MimeMessage(session);
//发送地址
message.setFrom(new InternetAddress(emailConfig.getFromAddress()));
//发送邮件给自己,解决发送邮件554的问题
message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())});
//接收地址
message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress());
//抄送地址
message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress());
//邮件主题
message.setSubject(mailData.getSubject());
//邮件内容
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(mailData.getContent(),mailData.getContent_type());
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
message.setSentDate(new Date());
//发送邮件
Transport.send(message);
}
@Override
public void doSendHtmlMailUseTemplate(MailData mailData) throws Exception {
/**创建一个邮件的会话**/
Authenticator authenticator = null;
if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器
authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword());
}
};
}
Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator);
/**创建邮件信心**/
Message message = new MimeMessage(session);
//发送地址
message.setFrom(new InternetAddress(emailConfig.getFromAddress()));
//发送邮件给自己,解决发送邮件554的问题
message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())});
//接收地址
message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress());
//抄送地址
message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress());
//邮件主题
message.setSubject(mailData.getSubject());
//邮件内容
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
String content = FreeMarkerUtil.getMailTextForTemplate(emailConfig.getTemplatePath(),mailData.getFileName(),mailData.getDataMap());
bodyPart.setContent(content,mailData.getContent_type());
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
message.setSentDate(new Date());
//发送邮件
Transport.send(message);
}
public EmailRepository( final MimeRegistry mimeRegistry,
final Session mailSession ) throws ContentIOException, MessagingException {
if ( mimeRegistry == null ) {
throw new NullPointerException();
}
this.mimeRegistry = mimeRegistry;
this.root = new EmailContentLocation( this, null, "" );
this.htmlEmail = new MimeMessage( mailSession );
this.bodypart = new MimeBodyPart();
this.multipart = new MimeMultipart( "related" );
this.multipart.addBodyPart( bodypart );
this.htmlEmail.setContent( multipart );
this.treatHtmlContentAsBody = true;
}
private void addImagePart() throws Exception {
data.nrEmbeddedImages = 0;
if ( data.embeddedMimePart != null && data.embeddedMimePart.size() > 0 ) {
for ( Iterator<MimeBodyPart> i = data.embeddedMimePart.iterator(); i.hasNext(); ) {
MimeBodyPart part = i.next();
data.parts.addBodyPart( part );
data.nrEmbeddedImages++;
}
}
}
private void print(MimeMessage message) throws MessagingException, IOException {
logger.debug("subject:" + message.getSubject());
logger.debug("description:" + message.getDescription());
logger.debug("contentType:" + message.getContentType());
logger.debug("sender:" + message.getSender());
logger.debug("from:" + Arrays.toString(message.getFrom()));
logger.debug("recipient:" + Arrays.toString(message.getAllRecipients()));
// logger.debug("description:"+message.);
// Enumeration allHeaderLines = message.getAllHeaderLines();
// while (allHeaderLines.hasMoreElements()) {
// logger.debug("allHeaderLines:"+allHeaderLines.nextElement());
// }
logger.debug("content:" + message.getContent());
logger.debug("content:" + message.getContent().getClass());
Multipart mp = (Multipart) message.getContent();
logger.debug("count:" + mp.getCount());
for (int i = 0; i < mp.getCount(); i++) {
MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i);
logger.debug("bodyPart content type:" + bodyPart.getContentType());
logger.debug("bodyPart content:" + bodyPart.getContent().getClass());
logger.debug("bodyPart content:" + bodyPart.getContent());
if (bodyPart.getContent() instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();
for (int j = 0; j < mimeMultipart.getCount(); j++) {
BodyPart part = mimeMultipart.getBodyPart(j);
logger.debug(i + " - bodyPart content type:" + part.getContentType());
logger.debug(i + " - bodyPart content:" + part.getContent().getClass());
logger.debug(i + " - bodyPart content:" + part.getContent());
}
}
}
}
private Object createMessageContent() throws IOException, MessagingException {
MimeMultipart content = new MimeMultipart();
MimeBodyPart contentText = new MimeBodyPart();
contentText.setText( "Hello World!" );
content.addBodyPart( contentText );
MimeBodyPart contentFile = new MimeBodyPart();
File testFile = TestUtils.getInputFile( "GetPOP", "txt" );
FileDataSource fds = new FileDataSource( testFile.getAbsolutePath() );
contentFile.setDataHandler( new DataHandler( fds ) );
contentFile.setFileName( testFile.getName() );
content.addBodyPart( contentFile );
return content;
}
/**
* Determine the MimeMultipart objects to use, which will be used
* to store attachments on the one hand and text(s) and inline elements
* on the other hand.
* <p>Texts and inline elements can either be stored in the root element
* itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED) or in a nested element
* rather than the root element directly (MULTIPART_MODE_MIXED_RELATED).
* <p>By default, the root MimeMultipart element will be of type "mixed"
* (MULTIPART_MODE_MIXED) or "related" (MULTIPART_MODE_RELATED).
* The main multipart element will either be added as nested element of
* type "related" (MULTIPART_MODE_MIXED_RELATED) or be identical to the root
* element itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED).
* @param mimeMessage the MimeMessage object to add the root MimeMultipart
* object to
* @param multipartMode the multipart mode, as passed into the constructor
* (MIXED, RELATED, MIXED_RELATED, or NO)
* @throws MessagingException if multipart creation failed
* @see #setMimeMultiparts
* @see #MULTIPART_MODE_NO
* @see #MULTIPART_MODE_MIXED
* @see #MULTIPART_MODE_RELATED
* @see #MULTIPART_MODE_MIXED_RELATED
*/
protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException {
switch (multipartMode) {
case MULTIPART_MODE_NO:
setMimeMultiparts(null, null);
break;
case MULTIPART_MODE_MIXED:
MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
mimeMessage.setContent(mixedMultipart);
setMimeMultiparts(mixedMultipart, mixedMultipart);
break;
case MULTIPART_MODE_RELATED:
MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
mimeMessage.setContent(relatedMultipart);
setMimeMultiparts(relatedMultipart, relatedMultipart);
break;
case MULTIPART_MODE_MIXED_RELATED:
MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
mimeMessage.setContent(rootMixedMultipart);
MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
MimeBodyPart relatedBodyPart = new MimeBodyPart();
relatedBodyPart.setContent(nestedRelatedMultipart);
rootMixedMultipart.addBodyPart(relatedBodyPart);
setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart);
break;
default:
throw new IllegalArgumentException("Only multipart modes MIXED_RELATED, RELATED and NO supported");
}
}
/**
* Add an attachment to the MimeMessage, taking the content from a
* {@code javax.activation.DataSource}.
* <p>Note that the InputStream returned by the DataSource implementation
* needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
* {@code getInputStream()} multiple times.
* @param attachmentFilename the name of the attachment as it will
* appear in the mail (the content type will be determined by this)
* @param dataSource the {@code javax.activation.DataSource} to take
* the content from, determining the InputStream and the content type
* @throws MessagingException in case of errors
* @see #addAttachment(String, org.springframework.core.io.InputStreamSource)
* @see #addAttachment(String, java.io.File)
*/
public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
Assert.notNull(attachmentFilename, "Attachment filename must not be null");
Assert.notNull(dataSource, "DataSource must not be null");
try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
getRootMimeMultipart().addBodyPart(mimeBodyPart);
}
catch (UnsupportedEncodingException ex) {
throw new MessagingException("Failed to encode attachment filename", ex);
}
}
public void addAttachment(String filepath, String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
javax.activation.DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}