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);
}
}
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 zm-mailbox by Zimbra.
the class ImapPartSpecifier method getContent.
private Pair<Long, InputStream> getContent(MimeMessage msg) throws BinaryDecodingException {
long length = -1;
InputStream is = null;
try {
MimePart mp = Mime.getMimePart(msg, part);
if (mp == null) {
return null;
}
// TEXT and HEADER* modifiers operate on rfc822 messages
if ((modifier.equals("TEXT") || modifier.startsWith("HEADER")) && !(mp instanceof MimeMessage)) {
// FIXME: hackaround for JavaMail's failure to handle multipart/digest properly
Object content = Mime.getMessageContent(mp);
if (!(content instanceof MimeMessage)) {
return null;
}
mp = (MimeMessage) content;
}
// get the content of the requested part
if (modifier.equals("")) {
if (mp instanceof MimeBodyPart) {
if (command.startsWith("BINARY")) {
try {
is = ((MimeBodyPart) mp).getInputStream();
} catch (IOException ioe) {
throw new BinaryDecodingException();
}
} else {
is = ((MimeBodyPart) mp).getRawInputStream();
length = Math.max(0, mp.getSize());
}
} else if (mp instanceof MimeMessage) {
if (!isMessageBody(msg, mp)) {
String parentPart = part.substring(0, Math.max(0, part.length() - 2));
return new ImapPartSpecifier(command, parentPart, "TEXT").getContent(msg);
} else if (command.startsWith("BINARY")) {
try {
is = ((MimeMessage) mp).getInputStream();
} catch (IOException ioe) {
throw new BinaryDecodingException();
}
} else {
is = ((MimeMessage) mp).getRawInputStream();
length = Math.max(0, mp.getSize());
}
} else {
ZimbraLog.imap.debug("getting content of part; not MimeBodyPart: " + this);
return ImapMessage.EMPTY_CONTENT;
}
} else if (modifier.startsWith("HEADER")) {
MimeMessage mm = (MimeMessage) mp;
Enumeration<?> headers;
if (modifier.equals("HEADER")) {
headers = mm.getAllHeaderLines();
} else if (modifier.equals("HEADER.FIELDS")) {
headers = mm.getMatchingHeaderLines(getHeaders());
} else {
headers = mm.getNonMatchingHeaderLines(getHeaders());
}
StringBuilder result = new StringBuilder();
while (headers.hasMoreElements()) {
result.append(headers.nextElement()).append(ImapHandler.LINE_SEPARATOR);
}
byte[] content = result.append(ImapHandler.LINE_SEPARATOR).toString().getBytes();
is = new ByteArrayInputStream(content);
length = content.length;
} else if (modifier.equals("MIME")) {
if (mp instanceof MimeMessage) {
String parentPart = part.substring(0, Math.max(0, part.length() - 2));
return new ImapPartSpecifier(command, parentPart, "HEADER").getContent(msg);
}
Enumeration<?> mime = mp.getAllHeaderLines();
StringBuilder result = new StringBuilder();
while (mime.hasMoreElements()) {
result.append(mime.nextElement()).append(ImapHandler.LINE_SEPARATOR);
}
byte[] content = result.append(ImapHandler.LINE_SEPARATOR).toString().getBytes();
is = new ByteArrayInputStream(content);
length = content.length;
} else if (modifier.equals("TEXT")) {
is = ((MimeMessage) mp).getRawInputStream();
length = Math.max(0, mp.getSize());
} else {
return null;
}
return new Pair<Long, InputStream>(length, is);
} catch (IOException e) {
ByteUtil.closeStream(is);
return null;
} catch (MessagingException e) {
ByteUtil.closeStream(is);
return null;
}
}
use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.
the class FeedManager method generateMessage.
private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr, Date date, List<Enclosure> attach) throws ServiceException {
// cull out invalid enclosures
if (attach != null) {
for (Iterator<Enclosure> it = attach.iterator(); it.hasNext(); ) {
if (it.next().getLocation() == null) {
it.remove();
}
}
}
boolean hasAttachments = attach != null && !attach.isEmpty();
// clean up whitespace in the title
if (title != null) {
title = title.replaceAll("\\s+", " ");
}
// create the MIME message and wrap it
try {
MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
body.setText(content, "utf-8");
body.setHeader("Content-Type", ctype);
if (hasAttachments) {
// encode each enclosure as an attachment with Content-Location set
MimeMultipart mmp = new ZMimeMultipart("mixed");
mmp.addBodyPart((BodyPart) body);
for (Enclosure enc : attach) {
MimeBodyPart part = new ZMimeBodyPart();
part.setText("");
part.addHeader("Content-Location", enc.getLocation());
part.addHeader("Content-Type", enc.getContentType());
if (enc.getDescription() != null) {
part.addHeader("Content-Description", enc.getDescription());
}
part.addHeader("Content-Disposition", "attachment");
mmp.addBodyPart(part);
}
mm.setContent(mmp);
}
mm.setSentDate(date);
mm.addFrom(new InternetAddress[] { addr });
mm.setSubject(title, "utf-8");
// more stuff here!
mm.saveChanges();
return new ParsedMessage(mm, date.getTime(), false);
} catch (MessagingException e) {
throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
}
}
use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.
the class ContentServlet method getCommand.
private void getCommand(HttpServletRequest req, HttpServletResponse resp, AuthToken token) throws ServletException, IOException {
ItemId iid = null;
try {
iid = new ItemId(req.getParameter(PARAM_MSGID), (String) null);
} catch (ServiceException e) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errInvalidId, req));
return;
}
String part = req.getParameter(PARAM_PART);
String fmt = req.getParameter(PARAM_FORMAT);
String dumpsterParam = req.getParameter(PARAM_DUMPSTER);
boolean fromDumpster = dumpsterParam != null && !dumpsterParam.equals("0") && !dumpsterParam.equalsIgnoreCase("false");
try {
// need to proxy the fetch if the mailbox lives on another server
if (!iid.isLocal()) {
// wrong server; proxy to the right one...
proxyServletRequest(req, resp, iid.getAccountId());
return;
}
String authId = token.getAccountId();
String accountId = iid.getAccountId() != null ? iid.getAccountId() : authId;
AccountUtil.addAccountToLogContext(Provisioning.getInstance(), accountId, ZimbraLog.C_NAME, ZimbraLog.C_ID, token);
if (!accountId.equalsIgnoreCase(authId))
ZimbraLog.addToContext(ZimbraLog.C_AID, authId);
Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(accountId);
if (mbox == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMailboxNotFound, req));
return;
}
ZimbraLog.addMboxToContext(mbox.getId());
MailItem item = mbox.getItemById(new OperationContext(token), iid.getId(), MailItem.Type.UNKNOWN, fromDumpster);
if (item == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMessageNotFound, req));
return;
}
try {
if (part == null) {
// they want the entire message...
boolean sync = "1".equals(req.getParameter(PARAM_SYNC));
StringBuffer hdr = new StringBuffer();
if (sync) {
// for sync, return metadata as headers to avoid extra SOAP round-trips
resp.addHeader("X-Zimbra-Tags", TagUtil.getTagIdString(item));
resp.addHeader("X-Zimbra-Tag-Names", TagUtil.encodeTags(item.getTags()));
resp.addHeader("X-Zimbra-Flags", item.getFlagString());
resp.addHeader("X-Zimbra-Received", Long.toString(item.getDate()));
resp.addHeader("X-Zimbra-Modified", Long.toString(item.getChangeDate()));
// also return metadata inline in the message content for now
hdr.append("X-Zimbra-Tags: ").append(TagUtil.getTagIdString(item)).append("\n");
hdr.append("X-Zimbra-Tag-Names: ").append(TagUtil.encodeTags(item.getTags()));
hdr.append("X-Zimbra-Flags: ").append(item.getFlagString()).append("\n");
hdr.append("X-Zimbra-Received: ").append(item.getDate()).append("\n");
hdr.append("X-Zimbra-Modified: ").append(item.getChangeDate()).append("\n");
}
if (item instanceof Message) {
Message msg = (Message) item;
if (sync) {
resp.addHeader("X-Zimbra-Conv", Integer.toString(msg.getConversationId()));
hdr.append("X-Zimbra-Conv: ").append(msg.getConversationId()).append("\n");
resp.getOutputStream().write(hdr.toString().getBytes());
}
resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
InputStream is = msg.getContentStream();
ByteUtil.copy(is, true, resp.getOutputStream(), false);
} else if (item instanceof CalendarItem) {
CalendarItem calItem = (CalendarItem) item;
if (sync) {
resp.getOutputStream().write(hdr.toString().getBytes());
}
resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
if (iid.hasSubpart()) {
int invId = iid.getSubpartId();
MimeMessage mm = calItem.getSubpartMessage(invId);
if (mm == null) {
// Backward compatibility for pre-5.0.16 ZDesktop: Build a MIME message on the fly.
Invite[] invs = calItem.getInvites(invId);
if (invs != null && invs.length > 0) {
Invite invite = invs[0];
mm = CalendarMailSender.createCalendarMessage(invite);
}
}
if (mm != null)
mm.writeTo(resp.getOutputStream());
} else {
InputStream is = calItem.getRawMessage();
if (is != null)
ByteUtil.copy(is, true, resp.getOutputStream(), false);
}
}
return;
} else {
MimePart mp = null;
if (item instanceof Message) {
mp = getMimePart((Message) item, part);
} else {
CalendarItem calItem = (CalendarItem) item;
if (iid.hasSubpart()) {
MimeMessage mbp = calItem.getSubpartMessage(iid.getSubpartId());
if (mbp != null)
mp = Mime.getMimePart(mbp, part);
} else {
mp = getMimePart(calItem, part);
}
}
if (mp != null) {
String contentType = mp.getContentType();
if (contentType == null) {
contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
}
if (contentType.toLowerCase().startsWith(MimeConstants.CT_TEXT_HTML) && (FORMAT_DEFANGED_HTML.equals(fmt) || FORMAT_DEFANGED_HTML_NOT_IMAGES.equals(fmt))) {
sendbackDefangedHtml(mp, contentType, resp, fmt);
} else {
if (!isTrue(Provisioning.A_zimbraAttachmentsViewInHtmlOnly, mbox.getAccountId())) {
sendbackOriginalDoc(mp, contentType, req, resp);
} else {
req.setAttribute(ATTR_MIMEPART, mp);
req.setAttribute(ATTR_MSGDIGEST, item.getDigest());
req.setAttribute(ATTR_CONTENTURL, req.getRequestURL().toString());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(CONVERSION_PATH);
dispatcher.forward(req, resp);
}
}
return;
}
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errPartNotFound, req));
}
} catch (MessagingException e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} catch (NoSuchItemException e) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, L10nUtil.getMessage(MsgKey.errNoSuchItem, req));
} catch (ServiceException e) {
returnError(resp, e);
} finally {
ZimbraLog.clearContext();
}
/*
out.println("hello world "+req.getParameter("id"));
out.println("path info: "+req.getPathInfo());
out.println("pathtrans: "+req.getPathTranslated());
*/
}
Aggregations