Search in sources :

Example 6 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project zm-mailbox by Zimbra.

the class SpamHandler method sendReport.

private void sendReport(SpamReport sr) throws ServiceException, MessagingException {
    Config config = Provisioning.getInstance().getConfig();
    String isSpamString = sr.isSpam ? config.getSpamReportTypeSpam() : config.getSpamReportTypeHam();
    SMTPMessage out = new SMTPMessage(JMSession.getSmtpSession());
    Mailbox mbox = MailboxManager.getInstance().getMailboxById(sr.mailboxId);
    Message msg = mbox.getMessageById(null, sr.messageId);
    MimeMultipart mmp = new ZMimeMultipart("mixed");
    MimeBodyPart infoPart = new ZMimeBodyPart();
    infoPart.setHeader("Content-Description", "Zimbra spam classification report");
    String body = String.format("Classified-By: %s\r\n" + "Classified-As: %s\r\n" + "Action: %s\r\n" + "Source-Folder: %s\r\n" + "Destination-Folder: %s\r\n" + "Destination-Mailbox: %s\r\n", Strings.nullToEmpty(sr.accountName), isSpamString, Strings.nullToEmpty(sr.action), Strings.nullToEmpty(sr.sourceFolder), Strings.nullToEmpty(sr.destFolder), Strings.nullToEmpty(sr.destAccountName));
    infoPart.setText(body);
    mmp.addBodyPart(infoPart);
    MailboxBlob blob = msg.getBlob();
    MimeBodyPart mbp = new ZMimeBodyPart();
    mbp.setDataHandler(new DataHandler(new MailboxBlobDataSource(blob)));
    mbp.setHeader("Content-Type", MimeConstants.CT_MESSAGE_RFC822);
    mbp.setHeader("Content-Disposition", Part.ATTACHMENT);
    mmp.addBodyPart(mbp);
    out.setContent(mmp);
    out.addHeader(config.getSpamReportSenderHeader(), sr.accountName);
    out.addHeader(config.getSpamReportTypeHeader(), isSpamString);
    if (config.isSmtpSendAddOriginatingIP() && sr.origIp != null)
        out.addHeader(MailSender.X_ORIGINATING_IP, MailSender.formatXOrigIpHeader(sr.origIp));
    out.setRecipient(javax.mail.Message.RecipientType.TO, sr.reportRecipient);
    out.setEnvelopeFrom(config.getSpamReportEnvelopeFrom());
    out.setSubject(config.getSpamTrainingSubjectPrefix() + " " + sr.accountName + ": " + isSpamString);
    Transport.send(out);
    ZimbraLog.misc.info("Sent " + sr);
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) Mailbox(com.zimbra.cs.mailbox.Mailbox) Message(com.zimbra.cs.mailbox.Message) SMTPMessage(com.sun.mail.smtp.SMTPMessage) MimeMessage(javax.mail.internet.MimeMessage) MailboxBlob(com.zimbra.cs.store.MailboxBlob) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MailboxBlobDataSource(com.zimbra.cs.mime.MailboxBlobDataSource) Config(com.zimbra.cs.account.Config) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) DataHandler(javax.activation.DataHandler) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 7 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage 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 8 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project adempiere by adempiere.

the class EMail method send.

/**
	 *	Send Mail direct
	 *	@return OK or error message
	 */
public String send() {
    log.info("(" + m_Host + ") " + m_from + " -> " + m_to);
    m_sentMsg = null;
    //
    if (!isValid(true)) {
        m_sentMsg = "Invalid Data";
        return m_sentMsg;
    }
    //	FR [ 402 ]
    Session session = null;
    try {
        session = getSession();
    } catch (SecurityException se) {
        log.log(Level.WARNING, "Auth=" + m_auth + " - " + se.toString());
        m_sentMsg = se.toString();
        return se.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Auth=" + m_auth, e);
        m_sentMsg = e.toString();
        return e.toString();
    }
    try {
        m_msg = new SMTPMessage(session);
        //	Addresses
        m_msg.setFrom(m_from);
        InternetAddress[] rec = getTos();
        if (rec.length == 1)
            m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
        else
            m_msg.setRecipients(Message.RecipientType.TO, rec);
        rec = getCcs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.CC, rec);
        rec = getBccs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.BCC, rec);
        if (m_replyTo != null)
            m_msg.setReplyTo(new Address[] { m_replyTo });
        //
        m_msg.setSentDate(new java.util.Date());
        m_msg.setHeader("Comments", "AdempiereMail");
        //	SMTP specifics
        m_msg.setAllow8bitMIME(true);
        //	Send notification on Failure & Success - no way to set envid in Java yet
        //	Bounce only header
        m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
        //
        setContent();
        m_msg.saveChanges();
        log.fine("message =" + m_msg);
        //
        getTransport(session);
        Transport.send(m_msg);
        log.fine("Success - MessageID=" + m_msg.getMessageID());
    } catch (MessagingException me) {
        Exception ex = me;
        StringBuffer sb = new StringBuffer("(ME)");
        boolean printed = false;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (!printed) {
                    if (invalid != null && invalid.length > 0) {
                        sb.append(" - Invalid:");
                        for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]);
                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null && validUnsent.length > 0) {
                        sb.append(" - ValidUnsent:");
                        for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]);
                    }
                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null && validSent.length > 0) {
                        sb.append(" - ValidSent:");
                        for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]);
                    }
                    printed = true;
                }
                if (sfex.getNextException() == null)
                    sb.append(" ").append(sfex.getLocalizedMessage());
            } else if (ex instanceof AuthenticationFailedException) {
                sb.append(" - Invalid Username/Password - " + m_auth);
            } else //	other MessagingException 
            {
                String msg = ex.getLocalizedMessage();
                if (msg == null)
                    sb.append(": ").append(ex.toString());
                else {
                    if (msg.indexOf("Could not connect to SMTP host:") != -1) {
                        int index = msg.indexOf('\n');
                        if (index != -1)
                            msg = msg.substring(0, index);
                        String cc = "??";
                        if (m_ctx != null)
                            cc = m_ctx.getProperty("#AD_Client_ID");
                        msg += " - AD_Client_ID=" + cc;
                    }
                    String className = ex.getClass().getName();
                    if (className.indexOf("MessagingException") != -1)
                        sb.append(": ").append(msg);
                    else
                        sb.append(" ").append(className).append(": ").append(msg);
                }
            }
            //	Next Exception
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (//	error loop
        ex != null);
        //
        if (CLogMgt.isLevelFinest())
            log.log(Level.WARNING, sb.toString(), me);
        else
            log.log(Level.WARNING, sb.toString());
        m_sentMsg = sb.toString();
        return sb.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        m_sentMsg = e.getLocalizedMessage();
        return e.getLocalizedMessage();
    }
    //
    if (CLogMgt.isLevelFinest())
        dumpMessage();
    m_sentMsg = SENT_OK;
    return m_sentMsg;
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) SendFailedException(javax.mail.SendFailedException) IOException(java.io.IOException) Session(javax.mail.Session)

Example 9 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project zm-mailbox by Zimbra.

the class ComputeAggregateQuotaUsage method sendWarnMsg.

private void sendWarnMsg(final Domain domain, ExecutorService executor) {
    final String[] recipients = domain.getDomainAggregateQuotaWarnEmailRecipient();
    if (ArrayUtil.isEmpty(recipients)) {
        return;
    }
    executor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                SMTPMessage out = new SMTPMessage(JMSession.getSmtpSession());
                // should From be configurable?
                out.setFrom(new JavaMailInternetAddress("Postmaster <postmaster@" + domain.getName() + ">"));
                for (String recipient : recipients) {
                    out.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(recipient));
                }
                out.setSentDate(new Date());
                // using default locale since not sure which locale to pick
                Locale locale = Locale.getDefault();
                out.setSubject(L10nUtil.getMessage(L10nUtil.MsgKey.domainAggrQuotaWarnMsgSubject, locale));
                out.setText(L10nUtil.getMessage(L10nUtil.MsgKey.domainAggrQuotaWarnMsgBody, locale, domain.getName(), domain.getAggregateQuotaLastUsage() / 1024.0 / 1024.0, domain.getDomainAggregateQuotaWarnPercent(), domain.getDomainAggregateQuota() / 1024.0 / 1024.0));
                Transport.send(out);
            } catch (Exception e) {
                ZimbraLog.misc.warn("Error in sending aggregate quota warning msg for domain %s", domain.getName(), e);
            }
        }
    });
}
Also used : Locale(java.util.Locale) SMTPMessage(com.sun.mail.smtp.SMTPMessage) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) Date(java.util.Date) ServiceException(com.zimbra.common.service.ServiceException)

Example 10 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project zm-mailbox by Zimbra.

the class JMSessionTest method testRelayMta.

//@Test
public void testRelayMta() throws Exception {
    Provisioning prov = Provisioning.getInstance();
    Server server = prov.getLocalServer();
    server.setShareNotificationMtaHostname("mta02.zimbra.com");
    server.setShareNotificationMtaPort(25);
    server.setShareNotificationMtaAuthRequired(true);
    server.setShareNotificationMtaConnectionType(ShareNotificationMtaConnectionType.STARTTLS);
    server.setShareNotificationMtaAuthAccount("test-jylee");
    server.setShareNotificationMtaAuthPassword("test123");
    SMTPMessage out = new SMTPMessage(JMSession.getRelaySession());
    InternetAddress address = new JavaMailInternetAddress("test-jylee@zimbra.com");
    out.setFrom(address);
    address = new JavaMailInternetAddress("test-jylee@zimbra.com");
    out.setRecipient(javax.mail.Message.RecipientType.TO, address);
    out.setSubject("test mail");
    out.setText("hello world");
    out.saveChanges();
    ZimbraLog.smtp.setLevel(Level.trace);
    Transport.send(out);
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) InternetAddress(javax.mail.internet.InternetAddress) Server(com.zimbra.cs.account.Server) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) MockProvisioning(com.zimbra.cs.account.MockProvisioning) Provisioning(com.zimbra.cs.account.Provisioning)

Aggregations

SMTPMessage (com.sun.mail.smtp.SMTPMessage)12 MessagingException (javax.mail.MessagingException)8 InternetAddress (javax.mail.internet.InternetAddress)8 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)6 Date (java.util.Date)6 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)5 MimeBodyPart (javax.mail.internet.MimeBodyPart)5 MimeMessage (javax.mail.internet.MimeMessage)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 Account (com.zimbra.cs.account.Account)3 Locale (java.util.Locale)3 Address (javax.mail.Address)3 Session (javax.mail.Session)3 IOException (java.io.IOException)2 DataHandler (javax.activation.DataHandler)2 Transport (javax.mail.Transport)2 AddressException (javax.mail.internet.AddressException)2 ServiceException (com.zimbra.common.service.ServiceException)1 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)1