下面列出了怎么用javax.mail.Part的API类实例代码及写法,或者点击链接到github查看源代码。
public void receiveTest() throws Exception {
MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
Address[] from = receivedMessages[0].getFrom();
assertEquals(1, from.length);
assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
assertEquals(toEmail,
((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());
MimeMultipart multipart = (MimeMultipart) receivedMessages[0].getContent();
Part part = null;
for(int i=0;i<multipart.getCount();i++) {
part = multipart.getBodyPart(i);
System.out.println(part.getFileName());
System.out.println(part.getSize());
}
}
@Test
void saveAttachmentShouldAddBinExtensionWhenNoFileNameExtension(TemporaryFolder temporaryFolder) throws Exception {
//Given
StripAttachment mailet = new StripAttachment();
FakeMailetConfig mci = FakeMailetConfig.builder()
.setProperty("directory", temporaryFolder.getFolderPath())
.setProperty("pattern", ".*")
.build();
mailet.init(mci);
Part part = MimeMessageBuilder.bodyPartBuilder().build();
String fileName = "exampleWithoutSuffix";
//When
Optional<String> maybeFilename = mailet.saveAttachmentToFile(part, Optional.of(fileName));
//Then
assertThat(maybeFilename).isPresent();
String filename = maybeFilename.get();
assertThat(filename).startsWith("exampleWithoutSuffix");
assertThat(filename).endsWith(".bin");
}
private void addBody(Part messagePart) throws MessagingException
{
if (body != null)
{
attachmentList.add(new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject() + " (part " + ++bodyNumber + ")", messagePart)));
if (log.isInfoEnabled())
{
log.info(String.format("Attachment \"%s\" has been added.", attachmentList.get(attachmentList.size() - 1).getFileName()));
}
}
else
{
body = new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject(), messagePart));
if (log.isDebugEnabled())
{
log.debug("Body has been added.");
}
}
}
/**
* Recursive find body parts and save them to HashMap
*/
private static void checkPartForTextType(HashMap<String, Collection<String>> bodies, Part part) throws IOException, MessagingException {
Object content = part.getContent();
if (content instanceof CharSequence) {
String ct = part.getContentType();
Collection<String> value = bodies.get(ct);
if (value != null) {
value.add(content.toString());
} else {
value = new LinkedList<>();
value.add(content.toString());
bodies.put(ct, value);
}
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
for(int i = 0; i < mp.getCount(); i++) {
checkPartForTextType(bodies, mp.getBodyPart(i));
}
}
}
public cfArrayData getBodyParts(){
try{
cfArrayData arr = cfArrayData.createArray( 1 );
if ( message.isMimeType("multipart/*") ){
Multipart mp = (Multipart)message.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
arr.addElement( new BlueDragonPartWrapper(mp.getBodyPart(i)) );
}else{
arr.addElement( new BlueDragonPartWrapper( (Part)message ) );
}
return arr;
}catch(Exception e){
return cfArrayData.createArray( 1 );
}
}
/**
* Find "text" parts of message recursively and appends it to sb StringBuilder
*
* @param multipart Multipart to process
* @param sb StringBuilder
* @throws MessagingException
* @throws IOException
*/
private void processMultiPart(Multipart multipart, StringBuilder sb) throws MessagingException, IOException
{
boolean isAlternativeMultipart = multipart.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE);
if (isAlternativeMultipart)
{
processAlternativeMultipart(multipart, sb);
}
else
{
for (int i = 0, n = multipart.getCount(); i < n; i++)
{
Part part = multipart.getBodyPart(i);
if (part.getContent() instanceof Multipart)
{
processMultiPart((Multipart) part.getContent(), sb);
}
else
{
processPart(part, sb);
}
}
}
}
/**
* Check if the body is from the content type and returns it if not attachment
*
* @param mimePart
* @param contentType
* @return null if not with specific content type or part is attachment
*/
private String getBodyIfNotAttachment(
BodyPart mimePart,
String contentType ) throws MessagingException, IOException {
String mimePartContentType = mimePart.getContentType().toLowerCase();
if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type
String contentDisposition = mimePart.getDisposition();
if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) {
Object partContent = mimePart.getContent();
if (partContent instanceof InputStream) {
return IoUtils.streamToString((InputStream) partContent);
} else {
return partContent.toString();
}
}
}
return null;
}
private List<String> getBodyText(Part part) throws MessagingException, IOException {
Object c = part.getContent();
if (c instanceof String) {
return UtilMisc.toList((String) c);
} else if (c instanceof Multipart) {
List<String> textContent = new ArrayList<>(); // SCIPIO: switched to ArrayList
int count = ((Multipart) c).getCount();
for (int i = 0; i < count; i++) {
BodyPart bp = ((Multipart) c).getBodyPart(i);
textContent.addAll(this.getBodyText(bp));
}
return textContent;
} else {
return new ArrayList<>(); // SCIPIO: switched to ArrayList
}
}
protected static void processMessagePartContent(Part part, Mail mail) throws MessagingException, IOException {
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
Attachment attachment = Attachment.from(part);
mail.attachments.add(attachment);
} else {
if (part.isMimeType("text/plain")) {
mail.text = (String) part.getContent();
} else if (part.isMimeType("text/html")) {
mail.html = (String) part.getContent();
}
}
}
private void GetPart(Part message) throws Exception {
if (message.isMimeType("text/plain")) {
Log.d(TAG,"+++ isMimeType text/plain (contentType):"+message.getContentType());
} else if (message.isMimeType("multipart/*")) {
Log.d(TAG,"+++ isMimeType multipart/* (contentType):"+message.getContentType());
Object content = message.getContent();
Multipart mp = (Multipart) content;
int count = mp.getCount();
for (int i = 0; i < count; i++) GetPart(mp.getBodyPart(i));
} else if (message.isMimeType("message/rfc822")) {
Log.d(TAG,"+++ isMimeType message/rfc822/* (contentType):"+message.getContentType());
GetPart((Part) message.getContent());
} else if (message.isMimeType("image/jpeg")) {
Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType());
} else if (message.getContentType().contains("image/")) {
Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType());
} else {
Object o = message.getContent();
if (o instanceof String) {
Log.d(TAG,"+++ instanceof String");
} else if (o instanceof InputStream) {
Log.d(TAG,"+++ instanceof InputStream");
} else Log.d(TAG,"+++ instanceof ???");
}
}
/**
* ����ʼ��ı�����
* @param part �ʼ���
* @param content �洢�ʼ��ı����ݵ��ַ���
*/
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
//������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж�
boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
if (part.isMimeType("text/*") && !isContainTextAttach) {
content.append(part.getContent().toString());
} else if (part.isMimeType("message/rfc822")) {
getMailTextContent((Part)part.getContent(),content);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
getMailTextContent(bodyPart,content);
}
}
}
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
DataSource source = new MyByteArrayDataSource(attachment.getContent());
String mimeType = FileTypesHelper.getMIMEType(attachment.getName());
String contentId = attachment.getContentId();
if (contentId == null) {
contentId = generateAttachmentContentId(attachment.getName());
}
String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
String charset = MimeUtility.mimeCharset(attachment.getEncoding() != null ?
attachment.getEncoding() : StandardCharsets.UTF_8.name());
String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, attachment.getName());
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
attachmentPart.setHeader("Content-Type", contentTypeValue);
attachmentPart.setFileName(attachment.getName());
attachmentPart.setDisposition(disposition);
return attachmentPart;
}
/**
* Get the content of a mail message.
*
* @param message
* the mail message
* @return the content of the mail message
*/
private String getMessageContent(Message message) throws MessagingException {
try {
Object content = message.getContent();
if (content instanceof Multipart) {
StringBuffer messageContent = new StringBuffer();
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
Part part = multipart.getBodyPart(i);
if (part.isMimeType("text/plain")) {
messageContent.append(part.getContent().toString());
}
}
return messageContent.toString();
}
return content.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private String getContent(Message msg) throws IOException, MessagingException {
Object messageContentObject = msg.getContent();
if (messageContentObject instanceof Multipart) {
Multipart multipart = (Multipart) msg.getContent();
// Loop over the parts of the email
for (int i = 0; i < multipart.getCount(); i++) {
// Retrieve the next part
Part part = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
&& StringUtils.isBlank(part.getFileName())) {
return part.getContent().toString();
}
}
} else {
return msg.getContent().toString().trim();
}
return "";
}
private List<String> getAttachments(Message msg) throws MessagingException, IOException {
Object messageContentObject = msg.getContent();
List<String> attachments = new ArrayList<>();
if (messageContentObject instanceof Multipart) {
Multipart multipart = (Multipart) msg.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
Part part = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())
&& StringUtils.isBlank(part.getFileName())) {
continue;
}
attachments.add(part.getFileName());
}
}
return attachments;
}
/**
* Get the String Content of a MimePart.
* @param p MimePart
* @return Content as String
* @throws IOException
* @throws MessagingException
*/
private static String getStringContent(Part p) throws IOException, MessagingException {
Object content = null;
try {
content = p.getContent();
} catch (Exception e) {
Logger.debug("Email body could not be read automatically (%s), we try to read it anyway.", e.toString());
// most likely the specified charset could not be found
content = p.getInputStream();
}
String stringContent = null;
if (content instanceof String) {
stringContent = (String) content;
} else if (content instanceof InputStream) {
stringContent = new String(ByteStreams.toByteArray((InputStream) content), "utf-8");
}
return stringContent;
}
public static String getFilename( Part Mess ) throws MessagingException{
// Part.getFileName() doesn't take into account any encoding that may have been
// applied to the filename so in order to obtain the correct filename we
// need to retrieve it from the Content-Disposition
String [] contentType = Mess.getHeader( "Content-Disposition" );
if ( contentType != null && contentType.length > 0 ){
int nameStartIndx = contentType[0].indexOf( "filename=\"" );
if ( nameStartIndx != -1 ){
String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) );
try {
filename = MimeUtility.decodeText( filename );
return filename;
} catch (UnsupportedEncodingException e) {}
}
}
// couldn't determine it using the above, so fall back to more reliable but
// less correct option
return Mess.getFileName();
}
/**
* 判断邮件中是否包含附件
*
* @param part part
* @return 邮件中存在附件返回true,不存在返回false
* @throws MessagingException MessagingException
* @throws IOException IOException
* @return boolean
*/
public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
boolean flag = false;
if (part.isMimeType("multipart/*")) {
MimeMultipart multipart = (MimeMultipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String disp = bodyPart.getDisposition();
if (disp != null
&& (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp
.equalsIgnoreCase(Part.INLINE))) {
flag = true;
} else if (bodyPart.isMimeType("multipart/*")) {
flag = isContainAttachment(bodyPart);
} else {
String contentType = bodyPart.getContentType();
if (contentType.indexOf("application") != -1) {
flag = true;
}
if (contentType.indexOf("name") != -1) {
flag = true;
}
}
if (flag)
break;
}
} else if (part.isMimeType("message/rfc822")) {
flag = isContainAttachment((Part) part.getContent());
}
return flag;
}
public static String getDisposition( Part _mess ) throws MessagingException{
String dispos = _mess.getDisposition();
// getDisposition isn't 100% reliable
if ( dispos == null ){
String [] disposHdr = _mess.getHeader( "Content-Disposition" );
if ( disposHdr != null && disposHdr.length > 0 && disposHdr[0].startsWith( Part.ATTACHMENT ) ){
return Part.ATTACHMENT;
}
}
return dispos;
}
/**
* Finds the suitable part from an multipart/alternative and appends it's text content to StringBuilder sb
*
* @param multipart
* @param sb
* @throws IOException
* @throws MessagingException
*/
private void processAlternativeMultipart(Multipart multipart, StringBuilder sb) throws IOException, MessagingException
{
Part partToUse = null;
for (int i = 0, n = multipart.getCount(); i < n; i++)
{
Part part = multipart.getBodyPart(i);
if (part.getContentType().contains(MimetypeMap.MIMETYPE_TEXT_PLAIN))
{
partToUse = part;
break;
}
else if (part.getContentType().contains(MimetypeMap.MIMETYPE_HTML))
{
partToUse = part;
}
else if (part.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE))
{
if (part.getContent() instanceof Multipart)
{
processAlternativeMultipart((Multipart) part.getContent(), sb);
}
}
}
if (partToUse != null)
{
processPart(partToUse, sb);
}
}
/**
* Finds text on a given mail part. Accepted parts types are text/html and text/plain.
* Attachments are ignored
*
* @param part
* @param sb
* @throws IOException
* @throws MessagingException
*/
private void processPart(Part part, StringBuilder sb) throws IOException, MessagingException
{
boolean isAttachment = Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition());
if (isAttachment)
{
return;
}
if (part.getContentType().contains(MimetypeMap.MIMETYPE_TEXT_PLAIN))
{
sb.append(part.getContent().toString());
}
else if (part.getContentType().contains(MimetypeMap.MIMETYPE_HTML))
{
String mailPartContent = part.getContent().toString();
//create a temporary html file with same mail part content and encoding
File tempHtmlFile = TempFileProvider.createTempFile("EMLTransformer_", ".html");
ContentWriter contentWriter = new FileContentWriter(tempHtmlFile);
contentWriter.setEncoding(getMailPartContentEncoding(part));
contentWriter.setMimetype(MimetypeMap.MIMETYPE_HTML);
contentWriter.putContent(mailPartContent);
//transform html file's content to plain text
EncodingAwareStringBean extractor = new EncodingAwareStringBean();
extractor.setCollapse(false);
extractor.setLinks(false);
extractor.setReplaceNonBreakingSpaces(false);
extractor.setURL(tempHtmlFile, contentWriter.getEncoding());
sb.append(extractor.getStrings());
tempHtmlFile.delete();
}
}
private boolean isPartAttachment(
MimePart part ) throws PackageException {
try {
String disposition = part.getDisposition();
if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
return true;
}
} catch (MessagingException me) {
throw new PackageException("Could not determine if part is an attachment", me);
}
return false;
}
public String getMessageBody() {
MimeMessage message = getMessage();
if (getMainPartCount() == 0) { // single part message
try {
Object content = message.getContent();
return getContentText(content);
} catch (Exception e) {
Debug.logError(e, module);
return null;
}
}
StringBuffer body = new StringBuffer();
for (int i = 0; i < getMainPartCount(); i++) {
int subPartCount = getSubPartCount(i);
String idx = Integer.toString(i);
if (subPartCount > 0) {
for (int si = 0; si < subPartCount; si++) {
String sidx = idx + "." + Integer.toString(si);
if (getPartContentType(sidx) != null && getPartContentType(sidx).toLowerCase(Locale.getDefault()).startsWith("text")) {
if (getPartDisposition(sidx) == null || getPartDisposition(sidx).equals(Part.INLINE)) {
body.append(getPartText(sidx)).append("\n");
}
}
}
} else {
if (getPartContentType(idx) != null && getPartContentType(idx).toLowerCase(Locale.getDefault()).startsWith("text")) {
// make sure the part isn't an attachment
if (getPartDisposition(idx) == null || getPartDisposition(idx).equals(Part.INLINE)) {
body.append(getPartText(idx)).append("\n");
}
}
}
}
return body.toString();
}
public String getMessageBodyContentType() {
String contentType = getContentType();
if (contentType != null && contentType.toLowerCase(Locale.getDefault()).startsWith("text")) {
return contentType;
}
for (int i = 0; i < getMainPartCount(); i++) {
int subPartCount = getSubPartCount(i);
String idx = Integer.toString(i);
if (subPartCount > 0) {
for (int si = 0; si < subPartCount; si++) {
String sidx = idx + "." + Integer.toString(si);
if (getPartContentType(sidx) != null && getPartContentType(sidx).toLowerCase(Locale.getDefault()).startsWith("text")) {
if (getPartDisposition(sidx) == null || getPartDisposition(sidx).equals(Part.INLINE)) {
return getPartContentType(sidx);
}
}
}
} else {
if (getPartContentType(idx) != null && getPartContentType(idx).toLowerCase(Locale.getDefault()).startsWith("text")) {
// make sure the part isn't an attachment
if (getPartDisposition(idx) == null || getPartDisposition(idx).equals(Part.INLINE)) {
return getPartContentType(idx);
}
}
}
}
return "text/html";
}
private static <T extends Part> void findBodyParts(Part part, Predicate<Part> filter, List<T> founds, String indent) throws MessagingException {
try {
addPart(filter, founds, indent, part);
Object content = part.getContent();
if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
LOG.trace("{}find {}", indent, mp.getContentType());
for (int i = 0; i < mp.getCount(); i++) {
findBodyParts(mp.getBodyPart(i), filter, founds, indent + " ");
}
}
} catch (IOException e) {
throw new MessagingException("Failed to access content of the mail", e);
}
}
@Test
public void messageWithSingleAttachmentOnly() throws Exception {
greenMail.setUser("[email protected]", "bpmn");
Session smtpSession = greenMail.getSmtp().createSession();
MimeMessage message = MailTestUtil.createMimeMessage(smtpSession);
message.setContent("text body", MailContentType.TEXT_PLAIN.getType());
message.setFileName("attachment.txt");
message.setDisposition(Part.ATTACHMENT);
GreenMailUtil.sendMimeMessage(message);
PollMailResponse response = MailConnectors.pollMails()
.createRequest()
.folder("INBOX")
.execute();
List<Mail> mails = response.getMails();
assertThat(mails).hasSize(1);
Mail mail = mails.get(0);
assertThat(mail.getAttachments()).hasSize(1);
Attachment mailAttachment = mail.getAttachments().get(0);
assertThat(mailAttachment.getFileName()).isEqualTo("attachment.txt");
assertThat(mailAttachment.getPath()).isNotNull();
}
@Test
void processMultipartPartMessageShouldReturnFalseWhenPartIsNotMultipart() throws Exception {
//Given
StripAttachment mailet = new StripAttachment();
Part part = new MimeBodyPart(new ByteArrayInputStream(new byte[0]));
Mail mail = mock(Mail.class);
//When
boolean actual = mailet.processMultipartPartMessage(part, mail);
//Then
assertThat(actual).isFalse();
}
public static EmailAttachment createTextAttachment(String text, String encoding, String name) {
byte[] data;
try {
data = text.getBytes(encoding);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return new EmailAttachment(data, name, null, Part.ATTACHMENT, encoding);
}
private void doTestTextAttachment(boolean useFs) throws IOException, MessagingException {
emailerConfig.setFileStorageUsed(useFs);
testMailSender.clearBuffer();
String attachmentText = "Test Attachment Text";
EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt");
EmailInfo myInfo = EmailInfoBuilder.create()
.setAddresses("[email protected]")
.setCaption("Test")
.setBody("Test")
.setAttachments(textAttach)
.build();
emailer.sendEmailAsync(myInfo);
emailer.processQueuedEmails();
MimeMessage msg = testMailSender.fetchSentEmail();
MimeBodyPart firstAttachment = getFirstAttachment(msg);
// check content bytes
Object content = firstAttachment.getContent();
assertTrue(content instanceof InputStream);
byte[] data = IOUtils.toByteArray((InputStream) content);
assertEquals(attachmentText, new String(data, "ISO-8859-1"));
// disposition
assertEquals(Part.ATTACHMENT, firstAttachment.getDisposition());
// charset header
String contentType = firstAttachment.getContentType();
assertTrue(contentType.toLowerCase().contains("charset=iso-8859-1"));
}
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException {
emailerConfig.setFileStorageUsed(useFs);
testMailSender.clearBuffer();
byte[] imageBytes = new byte[]{1, 2, 3, 4, 5};
String fileName = "logo.png";
EmailAttachment imageAttach = new EmailAttachment(imageBytes, fileName, "logo");
EmailInfo myInfo = EmailInfoBuilder.create()
.setAddresses("[email protected]")
.setCaption("Test")
.setBody("Test")
.setAttachments(imageAttach)
.build();
emailer.sendEmailAsync(myInfo);
emailer.processQueuedEmails();
MimeMessage msg = testMailSender.fetchSentEmail();
MimeBodyPart attachment = getInlineAttachment(msg);
// check content bytes
InputStream content = (InputStream) attachment.getContent();
byte[] data = IOUtils.toByteArray(content);
assertByteArrayEquals(imageBytes, data);
// disposition
assertEquals(Part.INLINE, attachment.getDisposition());
// mime type
String contentType = attachment.getContentType();
assertTrue(contentType.contains("image/png"));
}