use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.
the class ArchiveFormatter method saveItem.
private ArchiveOutputStream saveItem(UserServletContext context, MailItem mi, Map<Integer, String> fldrs, Map<Integer, Integer> cnts, boolean version, ArchiveOutputStream aos, CharsetEncoder charsetEncoder, Set<String> names) throws ServiceException {
String ext = null, name = null;
String extra = null;
Integer fid = mi.getFolderId();
String fldr;
InputStream is = null;
String metaParam = context.params.get(UserServlet.QP_META);
boolean meta = metaParam == null ? getDefaultMeta() : !metaParam.equals("0");
if (!version && mi.isTagged(Flag.FlagInfo.VERSIONED)) {
for (MailItem rev : context.targetMailbox.getAllRevisions(context.opContext, mi.getId(), mi.getType())) {
if (mi.getVersion() != rev.getVersion())
aos = saveItem(context, rev, fldrs, cnts, true, aos, charsetEncoder, names);
}
}
switch(mi.getType()) {
case APPOINTMENT:
Appointment appt = (Appointment) mi;
if (!appt.isPublic() && !appt.allowPrivateAccess(context.getAuthAccount(), context.isUsingAdminPrivileges())) {
return aos;
}
if (meta) {
name = appt.getSubject();
ext = "appt";
} else {
ext = "ics";
}
break;
case CHAT:
ext = "chat";
break;
case CONTACT:
Contact ct = (Contact) mi;
name = ct.getFileAsString();
if (!meta) {
ext = "vcf";
}
break;
case FLAG:
return aos;
case FOLDER:
case MOUNTPOINT:
case SEARCHFOLDER:
if (mi.getId() == Mailbox.ID_FOLDER_ROOT) {
name = "ROOT";
} else if (mi.getId() == Mailbox.ID_FOLDER_USER_ROOT) {
name = "USER_ROOT";
} else {
name = mi.getName();
}
break;
case MESSAGE:
Message msg = (Message) mi;
if (msg.hasCalendarItemInfos()) {
Set<ItemId> calItems = Sets.newHashSet();
for (Iterator<CalendarItemInfo> it = msg.getCalendarItemInfoIterator(); it.hasNext(); ) {
ItemId iid = it.next().getCalendarItemId();
if (iid != null) {
calItems.add(iid);
}
}
for (ItemId i : calItems) {
if (extra == null) {
extra = "calendar=" + i.toString();
} else {
extra += ',' + i.toString();
}
}
}
ext = "eml";
break;
case NOTE:
ext = "note";
break;
case TASK:
Task task = (Task) mi;
if (!task.isPublic() && !task.allowPrivateAccess(context.getAuthAccount(), context.isUsingAdminPrivileges())) {
return aos;
}
ext = "task";
break;
case VIRTUAL_CONVERSATION:
return aos;
case WIKI:
ext = "wiki";
break;
}
fldr = fldrs.get(fid);
if (fldr == null) {
Folder f = mi.getMailbox().getFolderById(context.opContext, fid);
cnts.put(fid, 1);
fldr = f.getPath();
if (fldr.startsWith("/")) {
fldr = fldr.substring(1);
}
fldr = sanitize(fldr, charsetEncoder);
fldr = ILLEGAL_FOLDER_CHARS.matcher(fldr).replaceAll("_");
fldrs.put(fid, fldr);
} else if (!(mi instanceof Folder)) {
final int BATCH = 500;
int cnt = cnts.get(fid) + 1;
cnts.put(fid, cnt);
cnt /= BATCH;
if (cnt > 0) {
fldr = fldr + '!' + cnt;
}
}
int targetBaseLength = 0;
if (context.noHierarchy()) {
// Parent hierarchy is not needed, so construct the folder names without parent hierarchy.
// e.g> represent "inbox/subfolder/target" as "target".
String targetPath = null;
if (context.itemPath.endsWith("/")) {
// inbox/subfolder/target/
targetPath = context.itemPath.substring(0, context.itemPath.lastIndexOf("/"));
} else {
// inbox/subfolder/target
targetPath = context.itemPath;
}
// "inbox/subfolder".length()
targetBaseLength = targetPath.lastIndexOf('/');
if (targetBaseLength >= fldr.length()) {
// fldr is "inbox/subfolder"
fldr = "";
} else if (targetBaseLength > 0) {
// fldr is "inbox/subfolder/target"
fldr = fldr.substring(targetBaseLength + 1);
}
}
try {
ArchiveOutputEntry aoe;
byte[] data = null;
String path = mi instanceof Contact ? getEntryName(mi, fldr, name, ext, charsetEncoder, names) : getEntryName(mi, fldr, name, ext, charsetEncoder, !(mi instanceof Document));
long miSize = mi.getSize();
if (miSize == 0 && mi.getDigest() != null) {
ZimbraLog.misc.debug("blob db size 0 for item %d", mi.getId());
return aos;
}
try {
is = mi.getContentStream();
} catch (Exception e) {
ZimbraLog.misc.error("missing blob for item %d: expected %d", mi.getId(), miSize);
return aos;
}
if (aos == null) {
aos = getOutputStream(context, charsetEncoder.charset().name());
}
if ((mi instanceof CalendarItem) && (context.getStartTime() != TIME_UNSPECIFIED || context.getEndTime() != TIME_UNSPECIFIED)) {
Collection<Instance> instances = ((CalendarItem) mi).expandInstances(context.getStartTime(), context.getEndTime(), false);
if (instances.isEmpty()) {
return aos;
}
}
aoe = aos.newOutputEntry(path + ".meta", mi.getType().toString(), mi.getType().toByte(), mi.getDate());
if (mi instanceof Message && (mi.getFlagBitmask() & Flag.ID_UNREAD) != 0) {
aoe.setUnread();
}
if (meta) {
ItemData itemData = new ItemData(mi, extra);
if (context.noHierarchy()) {
// itemData.path is of the form /Inbox/subfolder/target and after this step it becomes /target.
if (targetBaseLength > 0 && ((targetBaseLength + 1) < itemData.path.length())) {
itemData.path = itemData.path.substring(targetBaseLength + 1);
}
}
byte[] metaData = itemData.encode();
aoe.setSize(metaData.length);
aos.putNextEntry(aoe);
aos.write(metaData);
aos.closeEntry();
} else if (mi instanceof CalendarItem) {
Browser browser = HttpUtil.guessBrowser(context.req);
List<CalendarItem> calItems = new ArrayList<CalendarItem>();
boolean needAppleICalHacks = Browser.APPLE_ICAL.equals(browser);
boolean useOutlookCompatMode = Browser.IE.equals(browser);
OperationContext octxt = new OperationContext(context.getAuthAccount(), context.isUsingAdminPrivileges());
StringWriter writer = new StringWriter();
calItems.add((CalendarItem) mi);
context.targetMailbox.writeICalendarForCalendarItems(writer, octxt, calItems, useOutlookCompatMode, true, needAppleICalHacks, true);
data = writer.toString().getBytes(charsetEncoder.charset());
} else if (mi instanceof Contact) {
VCard vcf = VCard.formatContact((Contact) mi);
data = vcf.getFormatted().getBytes(charsetEncoder.charset());
} else if (mi instanceof Message) {
if (context.hasPart()) {
MimeMessage mm = ((Message) mi).getMimeMessage();
Set<String> attachmentNames = new HashSet<String>();
for (String part : context.getPart().split(",")) {
BufferStream bs;
MimePart mp = Mime.getMimePart(mm, part);
long sz;
if (mp == null) {
throw MailServiceException.NO_SUCH_PART(part);
}
name = Mime.getFilename(mp);
ext = null;
sz = mp.getSize();
if (sz == -1) {
sz = miSize;
}
if (name == null) {
name = "attachment";
} else {
int dot = name.lastIndexOf('.');
if (dot != -1 && dot < name.length() - 1) {
ext = name.substring(dot + 1);
name = name.substring(0, dot);
}
}
bs = new BufferStream(sz, 1024 * 1024);
InputStream stream = mp.getInputStream();
try {
bs.readFrom(stream);
} finally {
// close the stream, it could be an instance of PipedInputStream.
ByteUtil.closeStream(stream);
}
aoe = aos.newOutputEntry(getEntryName(mi, "", name, ext, charsetEncoder, attachmentNames), mi.getType().toString(), mi.getType().toByte(), mi.getDate());
sz = bs.getSize();
aoe.setSize(sz);
aos.putNextEntry(aoe);
bs.copyTo(aos.getOutputStream());
bs.close();
aos.closeEntry();
}
return aos;
}
}
aoe = aos.newOutputEntry(path, mi.getType().toString(), mi.getType().toByte(), mi.getDate());
if (data != null) {
aoe.setSize(data.length);
aos.putNextEntry(aoe);
aos.write(data);
aos.closeEntry();
} else if (is != null) {
if (context.shouldReturnBody()) {
byte[] buf = new byte[aos.getRecordSize() * 20];
int in;
long remain = miSize;
aoe.setSize(miSize);
aos.putNextEntry(aoe);
while (remain > 0 && (in = is.read(buf)) >= 0) {
aos.write(buf, 0, remain < in ? (int) remain : in);
remain -= in;
}
if (remain != 0) {
ZimbraLog.misc.error("mismatched blob size for item %d: expected %d", mi.getId(), miSize);
if (remain > 0) {
Arrays.fill(buf, (byte) ' ');
while (remain > 0) {
aos.write(buf, 0, remain < buf.length ? (int) remain : buf.length);
remain -= buf.length;
}
}
aos.closeEntry();
aoe = aos.newOutputEntry(path + ".err", mi.getType().toString(), mi.getType().toByte(), mi.getDate());
aoe.setSize(0);
aos.putNextEntry(aoe);
}
} else {
// Read headers into memory to compute size
byte[] headerData = HeadersOnlyInputStream.getHeaders(is);
aoe.setSize(headerData.length);
aos.putNextEntry(aoe);
aos.write(headerData);
}
aos.closeEntry();
}
} catch (Exception e) {
throw ServiceException.FAILURE("archive error", e);
} finally {
ByteUtil.closeStream(is);
}
return aos;
}
use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.
the class ToXML method addPart.
private static Element addPart(VisitPhase phase, Element parent, Element root, MPartInfo mpi, Set<MPartInfo> bodies, String prefix, int maxSize, boolean neuter, boolean excludeCalendarParts, String defaultCharset, boolean swallowContentExceptions, MsgContent wantContent) throws ServiceException {
if (phase == VisitPhase.POSTVISIT) {
return null;
}
String ctype = StringUtil.stripControlCharacters(mpi.getContentType());
if (excludeCalendarParts && MimeConstants.CT_TEXT_CALENDAR.equalsIgnoreCase(ctype)) {
// that happens to be a .ics file.
try {
ContentType ct = new ContentType(mpi.getMimePart().getContentType());
if (ct.getParameter("method") != null) {
return null;
}
} catch (MessagingException e) {
}
}
Element el = parent.addNonUniqueElement(MailConstants.E_MIMEPART);
MimePart mp = mpi.getMimePart();
String part = mpi.getPartName();
part = prefix + (prefix.isEmpty() || part.isEmpty() ? "" : ".") + part;
el.addAttribute(MailConstants.A_PART, part);
String fname = Mime.getFilename(mp);
if (MimeConstants.CT_XML_ZIMBRA_SHARE.equals(ctype)) {
// the <shr> share info goes underneath the top-level <m>
Element shr = root.addNonUniqueElement(MailConstants.E_SHARE_NOTIFICATION);
try {
addContent(shr, mpi, maxSize, defaultCharset);
} catch (IOException e) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing share XML", e);
} else {
LOG.warn("error writing body part", e);
}
} catch (MessagingException e) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing share XML", e);
}
}
} else if (MimeConstants.CT_XML_ZIMBRA_DL_SUBSCRIPTION.equals(ctype)) {
// the <dlSubs> dl subscription info goes underneath the top-level <m>
Element dlSubs = root.addNonUniqueElement(MailConstants.E_DL_SUBSCRIPTION_NOTIFICATION);
try {
addContent(dlSubs, mpi, maxSize, defaultCharset);
} catch (IOException e) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing DL subscription", e);
} else {
LOG.warn("error writing body part", e);
}
} catch (MessagingException e) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing DL subscription", e);
}
}
} else if (MimeConstants.CT_TEXT_ENRICHED.equals(ctype)) {
// we'll be replacing text/enriched with text/html
ctype = MimeConstants.CT_TEXT_HTML;
} else if (fname != null && (MimeConstants.CT_APPLICATION_OCTET_STREAM.equals(ctype) || MimeConstants.CT_APPLICATION_TNEF.equals(ctype))) {
String guess = MimeDetect.getMimeDetect().detect(fname);
if (guess != null) {
ctype = guess;
}
}
el.addAttribute(MailConstants.A_CONTENT_TYPE, ctype);
if (mpi.isMultipart()) {
// none of the below stuff is relevant for a multipart, so just return now...
return el;
}
// figure out attachment size
try {
el.addAttribute(MailConstants.A_SIZE, Mime.getSize(mp));
} catch (Exception e) {
// don't put out size if we get exception
ZimbraLog.mailbox.warn("Unable to determine MIME part size: %s", e.getMessage());
}
// figure out attachment disposition
try {
String disp = mp.getHeader("Content-Disposition", null);
if (disp != null) {
ContentDisposition cdisp = new ContentDisposition(MimeUtility.decodeText(disp));
el.addAttribute(MailConstants.A_CONTENT_DISPOSITION, StringUtil.stripControlCharacters(cdisp.getDisposition()));
}
} catch (MessagingException e) {
} catch (UnsupportedEncodingException e) {
}
// figure out attachment name
try {
if (fname == null && MimeConstants.CT_MESSAGE_RFC822.equals(ctype)) {
// "filename" for attached messages is the Subject
Object content = Mime.getMessageContent(mp);
if (content instanceof MimeMessage) {
fname = Mime.getSubject((MimeMessage) content);
}
}
if (!Strings.isNullOrEmpty(fname)) {
el.addAttribute(MailConstants.A_CONTENT_FILENAME, StringUtil.stripControlCharacters(fname));
}
} catch (MessagingException me) {
} catch (IOException ioe) {
}
// figure out content-id (used in displaying attached images)
String cid = mpi.getContentID();
if (cid != null) {
el.addAttribute(MailConstants.A_CONTENT_ID, StringUtil.stripControlCharacters(cid));
}
// figure out content-location (used in displaying attached images)
try {
String cl = mp.getHeader("Content-Location", null);
if (cl != null) {
el.addAttribute(MailConstants.A_CONTENT_LOCATION, StringUtil.stripControlCharacters(cl));
}
} catch (MessagingException e) {
}
// or if it was requested to include all parts
if (bodies == null || bodies.contains(mpi)) {
if (bodies != null) {
el.addAttribute(MailConstants.A_BODY, true);
}
try {
addContent(el, mpi, maxSize, neuter, defaultCharset, wantContent);
} catch (IOException e) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing part content", e);
} else {
LOG.warn("error writing body part", e);
}
} catch (MessagingException me) {
if (!swallowContentExceptions) {
throw ServiceException.FAILURE("error serializing part content", me);
}
}
}
return el;
}
use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.
the class CreateContact method parseAttachment.
private static Attachment parseAttachment(Element elt, String name, ZimbraSoapContext zsc, OperationContext octxt, Contact existing) throws ServiceException {
// check for uploaded attachment
String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
if (attachId != null) {
if (Contact.isSMIMECertField(name)) {
elt.setText(parseCertificate(elt, name, zsc, octxt, existing));
return null;
} else {
Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
UploadDataSource uds = new UploadDataSource(up);
return new Attachment(new DataHandler(uds), name, (int) up.getSize());
}
}
int itemId = (int) elt.getAttributeLong(MailConstants.A_ID, -1);
String part = elt.getAttribute(MailConstants.A_PART, null);
if (itemId != -1 || (part != null && existing != null)) {
MailItem item = itemId == -1 ? existing : getRequestedMailbox(zsc).getItemById(octxt, itemId, MailItem.Type.UNKNOWN);
try {
if (item instanceof Contact) {
Contact contact = (Contact) item;
if (part != null && !part.equals("")) {
try {
int partNum = Integer.parseInt(part) - 1;
if (partNum >= 0 && partNum < contact.getAttachments().size()) {
Attachment att = contact.getAttachments().get(partNum);
return new Attachment(att.getDataHandler(), name, att.getSize());
}
} catch (NumberFormatException nfe) {
}
throw ServiceException.INVALID_REQUEST("invalid contact part number: " + part, null);
} else {
VCard vcf = VCard.formatContact(contact);
return new Attachment(vcf.getFormatted().getBytes("utf-8"), "text/x-vcard; charset=utf-8", name, vcf.fn + ".vcf");
}
} else if (item instanceof Message) {
Message msg = (Message) item;
if (part != null && !part.equals("")) {
try {
MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
if (mp == null) {
throw MailServiceException.NO_SUCH_PART(part);
}
DataSource ds = new MimePartDataSource(mp);
return new Attachment(new DataHandler(ds), name);
} catch (MessagingException me) {
throw ServiceException.FAILURE("error parsing blob", me);
}
} else {
DataSource ds = new MessageDataSource(msg);
return new Attachment(new DataHandler(ds), name, (int) msg.getSize());
}
} else if (item instanceof Document) {
Document doc = (Document) item;
if (part != null && !part.equals("")) {
throw MailServiceException.NO_SUCH_PART(part);
}
DataSource ds = new DocumentDataSource(doc);
return new Attachment(new DataHandler(ds), name, (int) doc.getSize());
}
} catch (IOException ioe) {
throw ServiceException.FAILURE("error attaching existing item data", ioe);
} catch (MessagingException e) {
throw ServiceException.FAILURE("error attaching existing item data", e);
}
}
return null;
}
use of javax.mail.internet.MimePart in project jodd by oblac.
the class ReceivedEmail method processPart.
/**
* Process single part of received message. All parts are simple added to the message, i.e. hierarchy is not saved.
*/
protected void processPart(ReceivedEmail email, Part part) throws IOException, MessagingException {
Object content = part.getContent();
if (content instanceof String) {
String stringContent = (String) content;
String disposition = part.getDisposition();
if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
String contentType = part.getContentType();
String mimeType = EmailUtil.extractMimeType(contentType);
String encoding = EmailUtil.extractEncoding(contentType);
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
if (encoding == null) {
encoding = StringPool.US_ASCII;
}
email.addAttachment(fileName, mimeType, contentId, stringContent.getBytes(encoding));
} else {
String contentType = part.getContentType();
String encoding = EmailUtil.extractEncoding(contentType);
String mimeType = EmailUtil.extractMimeType(contentType);
if (encoding == null) {
encoding = StringPool.US_ASCII;
}
email.addMessage(stringContent, mimeType, encoding);
}
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
Part innerPart = mp.getBodyPart(i);
processPart(email, innerPart);
}
} else if (content instanceof InputStream) {
String fileName = EmailUtil.resolveFileName(part);
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
String mimeType = EmailUtil.extractMimeType(part.getContentType());
InputStream is = (InputStream) content;
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
} else if (content instanceof MimeMessage) {
MimeMessage mimeMessage = (MimeMessage) content;
addAttachmentMessage(new ReceivedEmail(mimeMessage));
} else {
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
String mimeType = EmailUtil.extractMimeType(part.getContentType());
InputStream is = part.getInputStream();
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
StreamUtil.close(is);
email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
}
}
use of javax.mail.internet.MimePart in project spring-framework by spring-projects.
the class MimeMessageHelper method setText.
/**
* Set the given text directly as content in non-multipart mode
* or as default body part in multipart mode.
* The "html" flag determines the content type to apply.
* <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 text the text for the message
* @param html whether to apply content type "text/html" for an
* HTML mail, using default content type ("text/plain") else
* @throws MessagingException in case of errors
*/
public void setText(String text, boolean html) throws MessagingException {
Assert.notNull(text, "Text must not be null");
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
} else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlTextToMimePart(partToUse, text);
} else {
setPlainTextToMimePart(partToUse, text);
}
}
Aggregations