Search in sources :

Example 46 with ZMimeMessage

use of com.zimbra.common.zmime.ZMimeMessage in project zm-mailbox by Zimbra.

the class Notification method assembleNotificationMessage.

private MimeMessage assembleNotificationMessage(Account account, Message msg, String rcpt, String destination, Session smtpSession) throws MessagingException {
    String recipientDomain = getDomain(rcpt);
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("SENDER_ADDRESS", ZInternetHeader.decode(msg.getSender()));
    vars.put("RECIPIENT_ADDRESS", rcpt);
    vars.put("RECIPIENT_DOMAIN", recipientDomain);
    vars.put("NOTIFICATION_ADDRESS", destination);
    vars.put("SUBJECT", msg.getSubject());
    vars.put("DATE", new MailDateFormat().format(new Date()));
    vars.put("NEWLINE", "\n");
    MimeMessage out = null;
    String template = account.getAttr(Provisioning.A_zimbraNewMailNotificationMessage, null);
    if (template != null) {
        String msgBody = StringUtil.fillTemplate(template, vars);
        InputStream is = new ByteArrayInputStream(msgBody.getBytes());
        out = new MimeMessage(smtpSession, is);
        InternetAddress address = new JavaMailInternetAddress(destination);
        out.setRecipient(javax.mail.Message.RecipientType.TO, address);
    } else {
        out = new ZMimeMessage(smtpSession);
        String from = account.getAttr(Provisioning.A_zimbraNewMailNotificationFrom);
        String subject = account.getAttr(Provisioning.A_zimbraNewMailNotificationSubject);
        String body = account.getAttr(Provisioning.A_zimbraNewMailNotificationBody);
        if (from == null || subject == null || body == null) {
            nfailed("null from, subject or body", destination, rcpt, msg);
            return null;
        }
        from = StringUtil.fillTemplate(from, vars);
        subject = StringUtil.fillTemplate(subject, vars);
        body = StringUtil.fillTemplate(body, vars);
        InternetAddress address = new JavaMailInternetAddress(from);
        out.setFrom(address);
        address = new JavaMailInternetAddress(destination);
        out.setRecipient(javax.mail.Message.RecipientType.TO, address);
        String charset = getCharset(account, subject);
        out.setSubject(subject, charset);
        charset = getCharset(account, body);
        out.setText(body, charset);
    }
    if (out != null) {
        out.setHeader("Auto-Submitted", "auto-replied (notification; " + rcpt + ")");
    }
    return out;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) HashMap(java.util.HashMap) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) MailDateFormat(javax.mail.internet.MailDateFormat) Date(java.util.Date)

Example 47 with ZMimeMessage

use of com.zimbra.common.zmime.ZMimeMessage in project zm-mailbox by Zimbra.

the class SpamExtract method extractMessages.

private static List<String> extractMessages(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) throws HttpException, IOException {
    List<String> extractedIds = new ArrayList<String>();
    gm.setPath(path);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Fetching " + path);
    }
    HttpClientUtil.executeMethod(hc, gm);
    if (gm.getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("HTTP GET failed: " + gm.getPath() + ": " + gm.getStatusCode() + ": " + gm.getStatusText());
    }
    ArchiveInputStream tgzStream = null;
    try {
        tgzStream = new TarArchiveInputStream(new GZIPInputStream(gm.getResponseBodyAsStream()), Charsets.UTF_8.name());
        ArchiveInputEntry entry = null;
        while ((entry = tgzStream.getNextEntry()) != null) {
            LOG.debug("got entry name %s", entry.getName());
            if (entry.getName().endsWith(".meta")) {
                ItemData itemData = new ItemData(readArchiveEntry(tgzStream, entry));
                UnderlyingData ud = itemData.ud;
                //.meta always followed by .eml
                entry = tgzStream.getNextEntry();
                if (raw) {
                    // Write the message as-is.
                    File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
                    OutputStream os = null;
                    try {
                        os = new BufferedOutputStream(new FileOutputStream(file));
                        byte[] data = readArchiveEntry(tgzStream, entry);
                        ByteUtil.copy(new ByteArrayInputStream(data), true, os, false);
                        if (verbose) {
                            LOG.info("Wrote: " + file);
                        }
                        extractedIds.add(ud.id + "");
                    } catch (java.io.IOException e) {
                        String fileName = outdir + "/" + mOutputPrefix + "-" + mExtractIndex;
                        LOG.error("Cannot write to " + fileName, e);
                    } finally {
                        if (os != null) {
                            os.close();
                        }
                    }
                } else {
                    // Write the attached message to the output directory.
                    BufferStream buffer = new BufferStream(entry.getSize(), MAX_BUFFER_SIZE);
                    buffer.setSequenced(false);
                    MimeMessage mm = null;
                    InputStream fis = null;
                    try {
                        byte[] data = readArchiveEntry(tgzStream, entry);
                        ByteUtil.copy(new ByteArrayInputStream(data), true, buffer, false);
                        if (buffer.isSpooled()) {
                            fis = new ZSharedFileInputStream(buffer.getFile());
                            mm = new ZMimeMessage(mJMSession, fis);
                        } else {
                            mm = new ZMimeMessage(mJMSession, buffer.getInputStream());
                        }
                        writeAttachedMessages(mm, outdir, entry.getName());
                        extractedIds.add(ud.id + "");
                    } catch (MessagingException me) {
                        LOG.warn("exception occurred fetching message", me);
                    } finally {
                        ByteUtil.closeStream(fis);
                    }
                }
            }
        }
    } finally {
        Closeables.closeQuietly(tgzStream);
    }
    return extractedIds;
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MessagingException(javax.mail.MessagingException) ArchiveInputEntry(com.zimbra.cs.service.formatter.ArchiveFormatter.ArchiveInputEntry) GZIPInputStream(java.util.zip.GZIPInputStream) TarArchiveInputStream(com.zimbra.cs.service.formatter.TarArchiveInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ArchiveInputStream(com.zimbra.cs.service.formatter.ArchiveFormatter.ArchiveInputStream) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) InputStream(java.io.InputStream) UnderlyingData(com.zimbra.cs.mailbox.MailItem.UnderlyingData) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) TarArchiveInputStream(com.zimbra.cs.service.formatter.TarArchiveInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) BufferStream(com.zimbra.common.util.BufferStream) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) TarArchiveInputStream(com.zimbra.cs.service.formatter.TarArchiveInputStream) ArchiveInputStream(com.zimbra.cs.service.formatter.ArchiveFormatter.ArchiveInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) ItemData(com.zimbra.cs.service.util.ItemData)

Example 48 with ZMimeMessage

use of com.zimbra.common.zmime.ZMimeMessage in project zm-mailbox by Zimbra.

the class TestMain method processMimeFile.

/**
     * @param mimeFile Name of original test file - used for diagnostic reporting
     * @param icalFile the file to write the ICALENDAR data to.
     * @param tnefFile the file to write TNEF data to.
     * @param recurInfoFile the file to write recurrence diagnostics data to.
     * @return true if successfully written data.
     */
private static boolean processMimeFile(File mimeFile, File icalFile, File tnefFile, File recurInfoFile, boolean verbose) {
    if (!mimeFile.exists()) {
        sLog.warn("Can't find MIME file %s", mimeFile.getPath());
        return false;
    }
    sLog.debug("Processing MIME file %s", mimeFile.getPath());
    // Prepare the input and output.
    InputStream fisMime = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
    Writer baosOut = null;
    boolean doneConversion = false;
    try {
        fisMime = new ZSharedFileInputStream(mimeFile);
        baosOut = new OutputStreamWriter(baos, UTF8);
        // Do the conversion.
        MimeMessage mm = new ZMimeMessage(JMSession.getSession(), fisMime);
        TnefToICalendar converter = getConverter();
        doneConversion = doConversion(mm, baosOut, converter, tnefFile, verbose);
        if (recurInfoFile != null) {
            if (converter instanceof DefaultTnefToICalendar) {
                DefaultTnefToICalendar tnef2ical = (DefaultTnefToICalendar) converter;
                RecurrenceDefinition recurDef = tnef2ical.getRecurDef();
                if (recurDef != null) {
                    FileWriter rsFileWriter = null;
                    try {
                        rsFileWriter = new FileWriter(recurInfoFile);
                        rsFileWriter.write(recurDef.toString());
                    } finally {
                        try {
                            if (rsFileWriter != null) {
                                rsFileWriter.close();
                            }
                        } catch (IOException e) {
                            sLog.error("Problem writing to recurInfo file %s", recurInfoFile, e);
                        }
                    }
                }
            }
        }
    } catch (UnsupportedTnefCalendaringMsgException ex) {
        sLog.warn("Unable to map %s to ICALENDAR", mimeFile.getPath(), ex);
        return false;
    } catch (TNEFtoIcalendarServiceException ex) {
        sLog.warn("Problem encountered mapping %s to ICALENDAR", mimeFile.getPath(), ex);
        return false;
    } catch (MessagingException ex) {
        sLog.warn("Problem encountered mapping %s to ICALENDAR", mimeFile.getPath(), ex);
        return false;
    } catch (ServiceException ex) {
        sLog.warn("Problem encountered mapping %s to ICALENDAR", mimeFile.getPath(), ex);
        return false;
    } catch (IOException ex) {
        sLog.warn("IO Problem encountered mapping %s to ICALENDAR", mimeFile.getPath(), ex);
        return false;
    } finally {
        try {
            if (fisMime != null)
                fisMime.close();
        } catch (IOException e) {
            sLog.error("Problem closing mime stream", e);
        }
    }
    if (!doneConversion) {
        return false;
    }
    if (!writeIcalendarData(mimeFile, baos, icalFile)) {
        return false;
    }
    if (!validateIcalendarData(mimeFile, baos)) {
        return false;
    }
    return true;
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) SharedFileInputStream(javax.mail.util.SharedFileInputStream) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) InputStream(java.io.InputStream) FileWriter(java.io.FileWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) ServiceException(com.zimbra.common.service.ServiceException) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) OutputStreamWriter(java.io.OutputStreamWriter) UnsupportedTnefCalendaringMsgException(com.zimbra.cs.util.tnef.TNEFtoIcalendarServiceException.UnsupportedTnefCalendaringMsgException) OutputStreamWriter(java.io.OutputStreamWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) RecurrenceDefinition(com.zimbra.cs.util.tnef.mapi.RecurrenceDefinition)

Example 49 with ZMimeMessage

use of com.zimbra.common.zmime.ZMimeMessage in project zm-mailbox by Zimbra.

the class TestMailSender method testRejectRecipient.

@Test
public void testRejectRecipient() throws Exception {
    String errorMsg = "Sender address rejected: User unknown in relay recipient table";
    String bogusAddress = TestUtil.getAddress("bogus");
    startDummySmtpServer(bogusAddress, errorMsg);
    Server server = Provisioning.getInstance().getLocalServer();
    server.setSmtpPort(TEST_SMTP_PORT);
    String content = TestUtil.getTestMessage(NAME_PREFIX + " testRejectSender", bogusAddress, SENDER_NAME, null);
    MimeMessage msg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(content.getBytes()));
    Mailbox mbox = TestUtil.getMailbox(SENDER_NAME);
    // Test reject first recipient, get partial send value from LDAP.
    boolean sendFailed = false;
    server.setSmtpSendPartial(false);
    try {
        mbox.getMailSender().sendMimeMessage(null, mbox, msg);
    } catch (MailServiceException e) {
        validateException(e, MailServiceException.SEND_ABORTED_ADDRESS_FAILURE, bogusAddress, errorMsg);
        sendFailed = true;
    }
    Assert.assertTrue(sendFailed);
    // Test reject first recipient, set partial send value explicitly.
    startDummySmtpServer(bogusAddress, errorMsg);
    sendFailed = false;
    server.setSmtpSendPartial(true);
    MailSender sender = mbox.getMailSender().setSendPartial(false);
    try {
        sender.sendMimeMessage(null, mbox, msg);
    } catch (MailServiceException e) {
        validateException(e, MailServiceException.SEND_ABORTED_ADDRESS_FAILURE, bogusAddress, errorMsg);
        sendFailed = true;
    }
    Assert.assertTrue(sendFailed);
    // Test reject second recipient, get partial send value from LDAP.
    startDummySmtpServer(bogusAddress, errorMsg);
    sendFailed = false;
    String validAddress = TestUtil.getAddress(RECIPIENT_NAME);
    InternetAddress[] recipients = new InternetAddress[2];
    recipients[0] = new JavaMailInternetAddress(validAddress);
    recipients[1] = new JavaMailInternetAddress(bogusAddress);
    msg.setRecipients(MimeMessage.RecipientType.TO, recipients);
    server.setSmtpSendPartial(false);
    try {
        mbox.getMailSender().sendMimeMessage(null, mbox, msg);
    } catch (MailServiceException e) {
        validateException(e, MailServiceException.SEND_ABORTED_ADDRESS_FAILURE, bogusAddress, errorMsg);
        sendFailed = true;
    }
    Assert.assertTrue(sendFailed);
    // Test partial send, get value from LDAP.
    startDummySmtpServer(bogusAddress, errorMsg);
    server.setSmtpSendPartial(true);
    sendFailed = false;
    try {
        mbox.getMailSender().sendMimeMessage(null, mbox, msg);
    } catch (MailServiceException e) {
        validateException(e, MailServiceException.SEND_PARTIAL_ADDRESS_FAILURE, bogusAddress, null);
        sendFailed = true;
    }
    Assert.assertTrue(sendFailed);
    // Test partial send, specify value explicitly.
    server.setSmtpSendPartial(false);
    startDummySmtpServer(bogusAddress, errorMsg);
    sendFailed = false;
    sender = mbox.getMailSender().setSendPartial(true);
    try {
        sender.sendMimeMessage(null, mbox, msg);
    } catch (MailServiceException e) {
        // Don't check error message.  JavaMail does not give us the SMTP protocol error in the
        // partial send case.
        validateException(e, MailServiceException.SEND_PARTIAL_ADDRESS_FAILURE, bogusAddress, null);
        sendFailed = true;
    }
    Assert.assertTrue(sendFailed);
}
Also used : JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) InternetAddress(javax.mail.internet.InternetAddress) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) Server(com.zimbra.cs.account.Server) Mailbox(com.zimbra.cs.mailbox.Mailbox) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) FixedMimeMessage(com.zimbra.cs.mime.Mime.FixedMimeMessage) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) MailSender(com.zimbra.cs.mailbox.MailSender) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) Test(org.junit.Test)

Example 50 with ZMimeMessage

use of com.zimbra.common.zmime.ZMimeMessage in project zm-mailbox by Zimbra.

the class TestMessageIntercept method compareContent.

/**
     * Confirm that the message attached to the intercept message matches the original.
     */
private void compareContent(ZMailbox tappedMbox, ZMessage tappedMsg, ZMailbox interceptorMbox, ZMessage interceptMsg) throws Exception {
    String relativeUrl = String.format("?id=%s&part=2", interceptMsg.getId());
    InputStream in = interceptorMbox.getRESTResource(relativeUrl);
    String interceptedMsgContent = new String(ByteUtil.getContent(in, -1)).trim();
    String tappedMsgContent = TestUtil.getContent(tappedMbox, tappedMsg.getId()).trim();
    Account account = TestUtil.getAccount(RECIPIENT_NAME);
    // Compare headers
    MimeMessage tappedMimeMsg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(tappedMsgContent.getBytes()));
    MimeMessage interceptedMimeMsg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(interceptedMsgContent.getBytes()));
    boolean headersOnly = account.getBooleanAttr(Provisioning.A_zimbraInterceptSendHeadersOnly, false);
    Set<String> tappedHeaderLines = getHeaderLines(tappedMimeMsg);
    Set<String> interceptedHeaderLines = getHeaderLines(interceptedMimeMsg);
    tappedHeaderLines.removeAll(getHeaderLines(interceptedMimeMsg));
    interceptedHeaderLines.removeAll(getHeaderLines(tappedMimeMsg));
    String context = "Unexpected headers found.  tapped: " + StringUtil.join(",", tappedHeaderLines) + ".  intercepted: " + StringUtil.join(",", interceptedHeaderLines) + ".";
    assertTrue(context, tappedHeaderLines.size() == 0 && interceptedHeaderLines.size() == 0);
    // Compare body
    if (headersOnly) {
        String interceptedBody = new String(ByteUtil.getContent(interceptedMimeMsg.getInputStream(), 0));
        if (interceptedBody != null) {
            interceptedBody = interceptedBody.trim();
        }
        assertTrue("Unexpected body: '" + interceptedBody + "'", interceptedBody == null || interceptedBody.length() == 0);
    } else {
        TestUtil.assertMessageContains(tappedMsgContent, interceptedMsgContent);
    }
}
Also used : Account(com.zimbra.cs.account.Account) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) InputStream(java.io.InputStream) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream)

Aggregations

ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)53 MimeMessage (javax.mail.internet.MimeMessage)50 Test (org.junit.Test)34 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)30 InputStream (java.io.InputStream)17 Session (javax.mail.Session)14 Transport (javax.mail.Transport)14 Mailbox (com.zimbra.cs.mailbox.Mailbox)13 ParsedMessage (com.zimbra.cs.mime.ParsedMessage)13 JMSession (com.zimbra.cs.util.JMSession)13 Message (com.zimbra.cs.mailbox.Message)12 Account (com.zimbra.cs.account.Account)10 MessagingException (javax.mail.MessagingException)10 OperationContext (com.zimbra.cs.mailbox.OperationContext)9 ItemId (com.zimbra.cs.service.util.ItemId)9 InternetAddress (javax.mail.internet.InternetAddress)9 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)8 DeliveryContext (com.zimbra.cs.mailbox.DeliveryContext)8 Date (java.util.Date)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6