Search in sources :

Example 61 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class RemoveAttachments method stripPart.

private static void stripPart(MimeMessage mm, String part) throws IOException, MessagingException, ServiceException {
    MimePart mp = mm;
    int dot = (part = part.trim()).lastIndexOf('.');
    if (dot > 0)
        mp = Mime.getMimePart(mm, part.substring(0, dot));
    if (mp == null)
        throw MailServiceException.NO_SUCH_PART(part);
    String subpart = dot > 0 ? part.substring(dot + 1) : part;
    if (subpart.equalsIgnoreCase("TEXT")) {
        if (!(mp instanceof MimeMessage))
            throw MailServiceException.NO_SUCH_PART(part);
        mp.setText("");
    } else {
        try {
            int partid = Integer.parseInt(subpart);
            if (Mime.getContentType(mp, MimeConstants.CT_DEFAULT).startsWith(MimeConstants.CT_MULTIPART_PREFIX)) {
                MimeMultipart mmp = Mime.getMultipartContent(mp, mp.getContentType());
                if (partid <= 0 || partid > mmp.getCount())
                    throw MailServiceException.NO_SUCH_PART(part);
                mmp.removeBodyPart(partid - 1);
            } else if (mp instanceof MimeMessage && partid == 1) {
                mp.setText("");
            } else {
                throw MailServiceException.NO_SUCH_PART(part);
            }
        } catch (NumberFormatException nfe) {
            throw ServiceException.INVALID_REQUEST("invalid part id: " + part, null);
        }
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimePart(javax.mail.internet.MimePart)

Example 62 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class SendDeliveryReport method sendReport.

public static void sendReport(Account authAccount, Message msg, boolean automatic, String requestHost, String userAgent) throws ServiceException {
    MimeMessage mm = msg.getMimeMessage();
    Account owner = msg.getMailbox().getAccount();
    String charset = authAccount.getPrefMailDefaultCharset();
    if (charset == null) {
        charset = MimeConstants.P_CHARSET_UTF8;
    }
    try {
        InternetAddress[] recipients = Mime.parseAddressHeader(mm, "Disposition-Notification-To");
        if (recipients == null || recipients.length == 0)
            return;
        SMTPMessage report = new SMTPMessage(JMSession.getSmtpSession());
        String subject = "Read-Receipt: " + msg.getSubject();
        report.setSubject(subject, CharsetUtil.checkCharset(subject, charset));
        report.setSentDate(new Date());
        report.setFrom(AccountUtil.getFriendlyEmailAddress(authAccount));
        report.addRecipients(javax.mail.Message.RecipientType.TO, recipients);
        report.setHeader("Auto-Submitted", "auto-replied (zimbra; read-receipt)");
        report.setHeader("Precedence", "bulk");
        if (Provisioning.getInstance().getConfig().isAutoSubmittedNullReturnPath()) {
            report.setEnvelopeFrom("<>");
        } else {
            report.setEnvelopeFrom(authAccount.getName());
        }
        MimeMultipart multi = new ZMimeMultipart("report");
        // part 1: human-readable notification
        String text = generateTextPart(owner, mm, authAccount.getLocale());
        MimeBodyPart mpText = new ZMimeBodyPart();
        mpText.setText(text, CharsetUtil.checkCharset(text, charset));
        multi.addBodyPart(mpText);
        // part 2: disposition notification
        String mdn = generateReport(owner, mm, automatic, requestHost, userAgent);
        MimeBodyPart mpMDN = new ZMimeBodyPart();
        mpMDN.setText(mdn, MimeConstants.P_CHARSET_UTF8);
        mpMDN.setHeader("Content-Type", "message/disposition-notification; charset=utf-8");
        multi.addBodyPart(mpMDN);
        //            // part 3: original message
        //            MimeBodyPart mpOriginal = new ZMimeBodyPart();
        //            mpOriginal.setDataHandler(new DataHandler(new BlobDataSource(msg.getBlob())));
        //            mpOriginal.setHeader("Content-Type", MimeConstants.CT_MESSAGE_RFC822);
        //            mpOriginal.setHeader("Content-Disposition", Part.ATTACHMENT);
        //            multi.addBodyPart(mpOriginal);
        report.setContent(multi);
        report.setHeader("Content-Type", multi.getContentType() + "; report-type=disposition-notification");
        report.saveChanges();
        Transport.send(report);
    } catch (MessagingException me) {
        throw ServiceException.FAILURE("error while sending read receipt", me);
    }
}
Also used : Account(com.zimbra.cs.account.Account) InternetAddress(javax.mail.internet.InternetAddress) SMTPMessage(com.sun.mail.smtp.SMTPMessage) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Date(java.util.Date)

Example 63 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class ParseMimeMessage method setMultipartContent.

private static void setMultipartContent(ContentType contentType, MimeMessage mm, MimeMultipart mmp, Element elem, MimeBodyPart[] alternatives, ParseMessageContext ctxt) throws MessagingException, ServiceException, IOException {
    // do we need to add a multipart/alternative for the alternatives?
    if (alternatives == null || contentType.getSubType().equals("alternative")) {
        // no need to add an extra multipart/alternative!
        // create the MimeMultipart and attach it to the existing structure:
        MimeMultipart mmpNew = new ZMimeMultipart(contentType);
        if (mmp == null) {
            // there were no multiparts at all, we need to create one
            mm.setContent(mmpNew);
        } else {
            // there was already a multipart/mixed at the top of the mm
            MimeBodyPart mbpWrapper = new ZMimeBodyPart();
            mbpWrapper.setContent(mmpNew);
            mmp.addBodyPart(mbpWrapper);
        }
        // add each part in turn (recursively) below
        for (Element subpart : elem.listElements()) {
            setContent(mm, mmpNew, subpart, null, ctxt);
        }
        // finally, add the alternatives if there are any...
        if (alternatives != null) {
            for (int i = 0; i < alternatives.length; i++) {
                ctxt.incrementSize("alternative", alternatives[i].getSize());
                mmpNew.addBodyPart(alternatives[i]);
            }
        }
    } else {
        // create a multipart/alternative to hold all the client's struct + the alternatives
        MimeMultipart mmpNew = new ZMimeMultipart("alternative");
        if (mmp == null) {
            mm.setContent(mmpNew);
        } else {
            MimeBodyPart mbpWrapper = new ZMimeBodyPart();
            mbpWrapper.setContent(mmpNew);
            mmp.addBodyPart(mbpWrapper);
        }
        // add the entire client's multipart/whatever here inside our multipart/alternative
        setContent(mm, mmpNew, elem, null, ctxt);
        // add all the alternatives
        for (int i = 0; i < alternatives.length; i++) {
            ctxt.incrementSize("alternative", alternatives[i].getSize());
            mmpNew.addBodyPart(alternatives[i]);
        }
    }
}
Also used : ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) Element(com.zimbra.common.soap.Element) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Mountpoint(com.zimbra.cs.mailbox.Mountpoint)

Example 64 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class Invite method getDescription.

/**
     * Returns the meeting notes.  Meeting notes is the text/plain part in an
     * invite.  It typically includes CUA-generated meeting summary as well as
     * text entered by the user.
     *
     * @return null if notes is not found
     * @throws ServiceException
     */
public static String getDescription(Part mmInv, String mimeType) throws ServiceException {
    if (mmInv == null)
        return null;
    try {
        // If top-level is text/calendar, parse the iCalendar object and return
        // the DESCRIPTION of the first VEVENT/VTODO encountered.
        String mmCtStr = mmInv.getContentType();
        if (mmCtStr != null) {
            ContentType mmCt = new ContentType(mmCtStr);
            if (mmCt.match(MimeConstants.CT_TEXT_CALENDAR)) {
                boolean wantHtml = MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(mimeType);
                Object mmInvContent = mmInv.getContent();
                InputStream is = null;
                try {
                    String charset = MimeConstants.P_CHARSET_UTF8;
                    if (mmInvContent instanceof InputStream) {
                        charset = mmCt.getParameter(MimeConstants.P_CHARSET);
                        if (charset == null)
                            charset = MimeConstants.P_CHARSET_UTF8;
                        is = (InputStream) mmInvContent;
                    } else if (mmInvContent instanceof String) {
                        String str = (String) mmInvContent;
                        charset = MimeConstants.P_CHARSET_UTF8;
                        is = new ByteArrayInputStream(str.getBytes(charset));
                    }
                    if (is != null) {
                        ZVCalendar iCal = ZCalendarBuilder.build(is, charset);
                        for (Iterator<ZComponent> compIter = iCal.getComponentIterator(); compIter.hasNext(); ) {
                            ZComponent component = compIter.next();
                            ICalTok compTypeTok = component.getTok();
                            if (compTypeTok == ICalTok.VEVENT || compTypeTok == ICalTok.VTODO) {
                                if (!wantHtml)
                                    return component.getPropVal(ICalTok.DESCRIPTION, null);
                                else
                                    return component.getDescriptionHtml();
                            }
                        }
                    }
                } finally {
                    ByteUtil.closeStream(is);
                }
            }
        }
        Object mmInvContent = mmInv.getContent();
        if (!(mmInvContent instanceof MimeMultipart)) {
            if (mmInvContent instanceof InputStream) {
                ByteUtil.closeStream((InputStream) mmInvContent);
            }
            return null;
        }
        MimeMultipart mm = (MimeMultipart) mmInvContent;
        // If top-level is multipart, get description from text/* part.
        int numParts = mm.getCount();
        String charset = null;
        for (int i = 0; i < numParts; i++) {
            BodyPart part = mm.getBodyPart(i);
            String ctStr = part.getContentType();
            try {
                ContentType ct = new ContentType(ctStr);
                if (ct.match(mimeType)) {
                    charset = ct.getParameter(MimeConstants.P_CHARSET);
                    if (charset == null)
                        charset = MimeConstants.P_CHARSET_DEFAULT;
                    byte[] descBytes = ByteUtil.getContent(part.getInputStream(), part.getSize());
                    return new String(descBytes, charset);
                }
                // If part is a multipart, recurse.
                if (ct.getBaseType().matches(MimeConstants.CT_MULTIPART_WILD)) {
                    String str = getDescription(part, mimeType);
                    if (str != null) {
                        return str;
                    }
                }
            } catch (javax.mail.internet.ParseException e) {
                ZimbraLog.calendar.warn("Invalid Content-Type found: \"" + ctStr + "\"; skipping part", e);
            }
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e);
    } catch (MessagingException e) {
        throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e);
    }
    return null;
}
Also used : BodyPart(javax.mail.BodyPart) ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ICalTok(com.zimbra.common.calendar.ZCalendar.ICalTok) ZComponent(com.zimbra.common.calendar.ZCalendar.ZComponent) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart)

Example 65 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class CalendarMailSender method createForwardNotifyMessage.

public static MimeMessage createForwardNotifyMessage(Account senderAcct, Account toAcct, String to, Address[] rcpts, Invite inv) throws MessagingException, ServiceException {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    Locale lc = toAcct.getLocale();
    mm.setSubject(L10nUtil.getMessage(MsgKey.calendarForwardNotificationSubject, lc, inv.getName()), MimeConstants.P_CHARSET_UTF8);
    mm.setSentDate(new Date());
    String postmaster = senderAcct.getAttr(Provisioning.A_zimbraNewMailNotificationFrom);
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("RECIPIENT_DOMAIN", senderAcct.getDomainName());
    postmaster = StringUtil.fillTemplate(postmaster, vars);
    mm.setSender(new JavaMailInternetAddress(postmaster));
    mm.setFrom(new JavaMailInternetAddress(senderAcct.getName()));
    mm.setRecipient(RecipientType.TO, new JavaMailInternetAddress(to));
    MimeMultipart mmp = new ZMimeMultipart("alternative");
    mm.setContent(mmp);
    String sender = senderAcct.getCn() + " <" + senderAcct.getName() + ">";
    String time = FriendlyCalendaringDescription.getTimeDisplayString(inv.getStartTime(), inv.getEndTime(), inv.isRecurrence(), inv.isAllDayEvent(), lc, toAcct);
    StringBuilder sb = new StringBuilder();
    StringBuilder sbHtml = new StringBuilder();
    for (Address rcpt : rcpts) {
        sb.append(rcpt.toString()).append("\n\t");
        InternetAddress address = new JavaMailInternetAddress(rcpt.toString());
        sbHtml.append("<a href=\"mailto:").append(address.getAddress()).append("\">");
        if (address.getPersonal() != null) {
            sbHtml.append(address.getPersonal()).append("</a>").append("<br>");
        } else {
            sbHtml.append(address.getAddress()).append("</a>").append("<br>");
        }
    }
    String recipients = sb.toString();
    String recipientsHtml = sbHtml.toString();
    if (inv.isRecurrence()) {
        ZRecur zr = FriendlyCalendaringDescription.getRecur(inv);
        time += " (" + FriendlyCalendaringDescription.getRecurrenceDisplayString(zr, inv.getStartTime().getCalendarCopy(), lc) + ")";
    }
    String text = L10nUtil.getMessage(MsgKey.calendarForwardNotificationBody, lc, sender, inv.getName(), time, recipients);
    MimeBodyPart textPart = new ZMimeBodyPart();
    textPart.setText(text, MimeConstants.P_CHARSET_UTF8);
    mmp.addBodyPart(textPart);
    sender = "<a href=\"mailto:" + senderAcct.getName() + "\">" + senderAcct.getCn() + "</a>";
    String html = L10nUtil.getMessage(MsgKey.calendarForwardNotificationBodyHtml, lc, sender, inv.getName(), time, recipientsHtml);
    MimeBodyPart htmlPart = new ZMimeBodyPart();
    htmlPart.setContent(html, MimeConstants.CT_TEXT_HTML + "; " + MimeConstants.P_CHARSET + "=" + MimeConstants.P_CHARSET_UTF8);
    mmp.addBodyPart(htmlPart);
    mm.saveChanges();
    return mm;
}
Also used : Locale(java.util.Locale) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) HashMap(java.util.HashMap) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) Date(java.util.Date) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Aggregations

MimeMultipart (javax.mail.internet.MimeMultipart)213 MimeBodyPart (javax.mail.internet.MimeBodyPart)134 MimeMessage (javax.mail.internet.MimeMessage)85 MessagingException (javax.mail.MessagingException)69 ByteArrayOutputStream (java.io.ByteArrayOutputStream)55 BodyPart (javax.mail.BodyPart)55 IOException (java.io.IOException)47 ByteString (com.linkedin.data.ByteString)37 DataHandler (javax.activation.DataHandler)33 InternetAddress (javax.mail.internet.InternetAddress)33 Test (org.testng.annotations.Test)31 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)27 HashMap (java.util.HashMap)27 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)26 Multipart (javax.mail.Multipart)26 Properties (java.util.Properties)25 Session (javax.mail.Session)24 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)24 InputStream (java.io.InputStream)23 Date (java.util.Date)21