Search in sources :

Example 16 with AddressException

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

the class Notification method outOfOfficeIfNecessary.

/**
     * If the recipient's account requires out of office notification,
     * send it out.  We send these out based on users' setting, and
     * the incoming message meeting certain criteria.
     */
private void outOfOfficeIfNecessary(Account account, Mailbox mbox, MimeMessage mm, Integer msgId, String rcpt, String envSenderString) throws ServiceException, MessagingException {
    boolean replyEnabled = account.isPrefOutOfOfficeReplyEnabled();
    if (ZimbraLog.mailbox.isDebugEnabled()) {
        ZimbraLog.mailbox.debug("outofoffice reply enabled=" + replyEnabled + " rcpt='" + rcpt + "' mid=" + msgId);
    }
    if (!replyEnabled) {
        return;
    }
    // Check if we are in any configured out of office interval
    Date now = new Date();
    Date fromDate = account.getGeneralizedTimeAttr(Provisioning.A_zimbraPrefOutOfOfficeFromDate, null);
    if (fromDate != null && now.before(fromDate)) {
        ofailed("from date not reached", null, rcpt, msgId);
        return;
    }
    Date untilDate = account.getGeneralizedTimeAttr(Provisioning.A_zimbraPrefOutOfOfficeUntilDate, null);
    if (untilDate != null && now.after(untilDate)) {
        ofailed("until date reached", null, rcpt, msgId);
        return;
    }
    // If envelope sender is empty
    if (envSenderString == null) {
        ofailed("envelope sender null", null, rcpt, msgId);
        return;
    }
    if (envSenderString.length() < 1) {
        // be conservative
        ofailed("envelope sender empty", null, rcpt, msgId);
        return;
    }
    InternetAddress envSender;
    try {
        // NB: 'strict' being 'true' causes <> to except
        envSender = new JavaMailInternetAddress(envSenderString, true);
    } catch (AddressException ae) {
        ofailed("envelope sender invalid", envSenderString, rcpt, msgId, ae);
        return;
    }
    String destination = envSender.getAddress();
    if (Mime.isAutoSubmitted(mm)) {
        ofailed("auto-submitted not no", destination, rcpt, msgId);
        return;
    }
    // If precedence is bulk, junk or list
    String[] precedence = mm.getHeader("Precedence");
    if (hasPrecedence(precedence, "bulk")) {
        ofailed("precedence bulk", destination, rcpt, msgId);
        return;
    } else if (hasPrecedence(precedence, "junk")) {
        ofailed("precedence junk", destination, rcpt, msgId);
        return;
    } else if (hasPrecedence(precedence, "list")) {
        ofailed("precedence list", destination, rcpt, msgId);
        return;
    }
    // Check if the envelope sender indicates a mailing list owner and such
    String[] envSenderAddrParts = EmailUtil.getLocalPartAndDomain(destination);
    if (envSenderAddrParts == null) {
        ofailed("envelope sender invalid", destination, rcpt, msgId);
        return;
    }
    String envSenderLocalPart = envSenderAddrParts[0];
    envSenderLocalPart = envSenderLocalPart.toLowerCase();
    if (envSenderLocalPart.startsWith("owner-") || envSenderLocalPart.endsWith("-owner")) {
        ofailed("envelope sender has owner- or -owner", destination, rcpt, msgId);
        return;
    }
    if (envSenderLocalPart.contains("-request")) {
        ofailed("envelope sender contains -request", destination, rcpt, msgId);
        return;
    }
    if (envSenderLocalPart.equals("mailer-daemon")) {
        ofailed("envelope sender is mailer-daemon", destination, rcpt, msgId);
        return;
    }
    if (envSenderLocalPart.equals("majordomo")) {
        ofailed("envelope sender is majordomo", destination, rcpt, msgId);
        return;
    }
    if (envSenderLocalPart.equals("listserv")) {
        ofailed("envelope sender is listserv", destination, rcpt, msgId);
        return;
    }
    // multipart/report is also machine generated
    String ct = mm.getContentType();
    if (ct != null && ct.equalsIgnoreCase("multipart/report")) {
        ofailed("content-type multipart/report", destination, rcpt, msgId);
        return;
    }
    // Check if recipient was directly mentioned in to/cc of this message
    String[] otherAccountAddrs = account.getMultiAttr(Provisioning.A_zimbraPrefOutOfOfficeDirectAddress);
    if (!AccountUtil.isDirectRecipient(account, otherAccountAddrs, mm, OUT_OF_OFFICE_DIRECT_CHECK_NUM_RECIPIENTS)) {
        ofailed("not direct", destination, rcpt, msgId);
        return;
    }
    // If we've already sent to this user, do not send again
    DbConnection conn = null;
    try {
        conn = DbPool.getConnection(mbox);
        if (DbOutOfOffice.alreadySent(conn, mbox, destination, account.getTimeInterval(Provisioning.A_zimbraPrefOutOfOfficeCacheDuration, DEFAULT_OUT_OF_OFFICE_CACHE_DURATION_MILLIS))) {
            ofailed("already sent", destination, rcpt, msgId);
            return;
        }
    } finally {
        DbPool.quietClose(conn);
    }
    // Send the message
    try {
        SMTPMessage out = new SMTPMessage(JMSession.getSmtpSession());
        // Set From and Reply-To.
        out.setFrom(AccountUtil.getFromAddress(account));
        InternetAddress replyTo = AccountUtil.getReplyToAddress(account);
        if (replyTo != null) {
            out.setReplyTo(new Address[] { replyTo });
        }
        // To
        out.setRecipient(javax.mail.Message.RecipientType.TO, envSender);
        // Date
        out.setSentDate(new Date());
        // Subject
        String subject = Mime.getSubject(mm);
        String replySubjectPrefix = L10nUtil.getMessage(L10nUtil.MsgKey.replySubjectPrefix, account.getLocale());
        if (subject == null) {
            subject = replySubjectPrefix;
        } else if (!subject.toLowerCase().startsWith(replySubjectPrefix.toLowerCase())) {
            subject = replySubjectPrefix + " " + subject;
        }
        String charset = getCharset(account, subject);
        out.setSubject(subject, charset);
        // In-Reply-To
        String messageId = mm.getMessageID();
        if (messageId != null && !messageId.trim().equals("")) {
            out.setHeader("In-Reply-To", messageId);
        }
        // Auto-Submitted
        out.setHeader("Auto-Submitted", "auto-replied (zimbra; vacation)");
        // Precedence (discourage older systems from responding)
        out.setHeader("Precedence", "bulk");
        // check whether to send "external" OOO reply
        if (account.isPrefOutOfOfficeSuppressExternalReply() && isOfExternalSenderType(destination, account, mbox) && !isInternalSender(destination, account)) {
            ZimbraLog.mailbox.info(destination + " is external user and no external reply option is set, so no OOO will be sent. ");
            return;
        }
        boolean sendExternalReply = account.isPrefOutOfOfficeExternalReplyEnabled() && !isInternalSender(destination, account) && isOfExternalSenderType(destination, account, mbox);
        String body = account.getAttr(sendExternalReply ? Provisioning.A_zimbraPrefOutOfOfficeExternalReply : Provisioning.A_zimbraPrefOutOfOfficeReply, "");
        charset = getCharset(account, body);
        out.setText(body, charset);
        if (Provisioning.getInstance().getConfig().getBooleanAttr(Provisioning.A_zimbraAutoSubmittedNullReturnPath, true)) {
            out.setEnvelopeFrom("<>");
        } else {
            out.setEnvelopeFrom(account.getName());
        }
        MailSender sender = mbox.getMailSender();
        sender.setSaveToSent(false);
        sender.setDsnNotifyOptions(MailSender.DsnNotifyOption.NEVER);
        sender.sendMimeMessage(null, mbox, out);
        ZimbraLog.mailbox.info("outofoffice sent dest='" + destination + "' rcpt='" + rcpt + "' mid=" + msgId);
        // Save so we will not send to again
        try {
            conn = DbPool.getConnection(mbox);
            DbOutOfOffice.setSentTime(conn, mbox, destination);
            conn.commit();
        } finally {
            DbPool.quietClose(conn);
        }
    } catch (MessagingException me) {
        ofailed("send failed", destination, rcpt, msgId, me);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) SMTPMessage(com.sun.mail.smtp.SMTPMessage) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) Date(java.util.Date) DbConnection(com.zimbra.cs.db.DbPool.DbConnection)

Example 17 with AddressException

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

the class CalendarMailSender method createOrganizerChangeMessage.

public static MimeMessage createOrganizerChangeMessage(Account fromAccount, Account authAccount, boolean asAdmin, CalendarItem calItem, Invite inv, List<Address> rcpts) throws ServiceException {
    ZOrganizer organizer = inv.getOrganizer();
    assert (organizer != null);
    boolean onBehalfOf = organizer.hasSentBy();
    String senderAddr = onBehalfOf ? organizer.getSentBy() : organizer.getAddress();
    Locale locale = fromAccount.getLocale();
    boolean hidePrivate = !calItem.isPublic() && !calItem.allowPrivateAccess(authAccount, asAdmin);
    String subject;
    if (hidePrivate) {
        subject = L10nUtil.getMessage(MsgKey.calendarSubjectWithheld, locale);
    } else {
        subject = inv.getName();
    }
    StringBuilder sb = new StringBuilder("Organizer has been changed to " + fromAccount.getName());
    sb.append("\r\n\r\n");
    if (!hidePrivate) {
        MimeMessage mmInv = inv.getMimeMessage();
        if (mmInv != null) {
            attachInviteSummary(sb, inv, mmInv, locale);
        }
    }
    ZVCalendar iCal = inv.newToICalendar(true);
    Address from = AccountUtil.getFriendlyEmailAddress(fromAccount);
    Address sender = null;
    if (onBehalfOf) {
        try {
            sender = new JavaMailInternetAddress(senderAddr);
        } catch (AddressException e) {
            throw MailServiceException.ADDRESS_PARSE_ERROR(e);
        }
    }
    return createCalendarMessage(authAccount, from, sender, rcpts, subject, sb.toString(), null, inv.getUid(), iCal);
}
Also used : Locale(java.util.Locale) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress)

Example 18 with AddressException

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

the class CalendarMailSender method createForwardedInviteMessage.

public static MimeMessage createForwardedInviteMessage(MimeMessage mmOrig, String origSenderEmail, String forwarderEmail, String[] forwardTo) {
    List<Address> rcpts = new ArrayList<Address>();
    for (String to : forwardTo) {
        try {
            rcpts.add(new JavaMailInternetAddress(to));
        } catch (AddressException e) {
            ZimbraLog.calendar.warn("Ignoring invalid address \"" + to + "\" during invite forward");
        }
    }
    if (rcpts.isEmpty())
        return null;
    MimeMessage mm = null;
    try {
        mm = new ZMimeMessage(mmOrig);
        mm.removeHeader("To");
        mm.removeHeader("Cc");
        mm.removeHeader("Bcc");
        mm.addRecipients(RecipientType.TO, rcpts.toArray(new Address[0]));
        // Set Reply-To to the original sender.
        mm.setReplyTo(new Address[] { new JavaMailInternetAddress(origSenderEmail) });
        mm.removeHeader("Date");
        mm.removeHeader("Message-ID");
        mm.removeHeader("Return-Path");
        mm.removeHeader("Received");
        // Set special header to indicate the forwarding attendee.
        mm.setHeader(CalendarMailSender.X_ZIMBRA_CALENDAR_INTENDED_FOR, forwarderEmail);
        mm.saveChanges();
    } catch (MessagingException e) {
        ZimbraLog.calendar.warn("Unable to compose email for invite forwarding", e);
    }
    return mm;
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) ArrayList(java.util.ArrayList) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress)

Example 19 with AddressException

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

the class CalendarMailSender method createForwardedPrivateInviteMessage.

public static MimeMessage createForwardedPrivateInviteMessage(Account account, Locale lc, String method, List<Invite> invites, String origSenderEmail, String forwarderEmail, String[] forwardTo) throws ServiceException {
    if (invites == null || invites.isEmpty())
        return null;
    List<Address> rcpts = new ArrayList<Address>();
    for (String to : forwardTo) {
        try {
            rcpts.add(new JavaMailInternetAddress(to));
        } catch (AddressException e) {
            ZimbraLog.calendar.warn("Ignoring invalid address \"" + to + "\" during invite forward");
        }
    }
    if (rcpts.isEmpty())
        return null;
    String subject = L10nUtil.getMessage(MsgKey.calendarSubjectWithheld, lc);
    // Create filtered version of invites.
    List<Invite> filteredInvs = new ArrayList<Invite>();
    for (Invite inv : invites) {
        Invite filtered = inv.newCopy();
        filtered.clearAlarms();
        filtered.clearPrivateInfo();
        filtered.setName(subject);
        // Add ATTENDEE for forwarder.
        List<ZAttendee> atts = inv.getAttendees();
        if (atts != null && forwarderEmail != null) {
            for (ZAttendee att : atts) {
                if (forwarderEmail.equalsIgnoreCase(att.getAddress())) {
                    filtered.addAttendee(att);
                }
            }
        }
        filteredInvs.add(filtered);
    }
    MimeMessage mm = null;
    try {
        mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(account));
        mm.setFrom(new JavaMailInternetAddress(origSenderEmail));
        mm.addRecipients(RecipientType.TO, rcpts.toArray(new Address[0]));
        // Set special header to indicate the forwarding attendee.
        mm.setHeader(CalendarMailSender.X_ZIMBRA_CALENDAR_INTENDED_FOR, forwarderEmail);
        mm.setSubject(subject);
        StringWriter writer = new StringWriter();
        try {
            writer.write("BEGIN:VCALENDAR\r\n");
            ZProperty prop;
            prop = new ZProperty(ICalTok.PRODID, ZCalendar.sZimbraProdID);
            prop.toICalendar(writer);
            prop = new ZProperty(ICalTok.VERSION, ZCalendar.sIcalVersion);
            prop.toICalendar(writer);
            prop = new ZProperty(ICalTok.METHOD, method);
            prop.toICalendar(writer);
            // timezones
            Invite firstInv = filteredInvs.get(0);
            TimeZoneMap tzmap = new TimeZoneMap(firstInv.getTimeZoneMap().getLocalTimeZone());
            for (Invite inv : filteredInvs) {
                tzmap.add(inv.getTimeZoneMap());
            }
            for (Iterator<ICalTimeZone> iter = tzmap.tzIterator(); iter.hasNext(); ) {
                ICalTimeZone tz = iter.next();
                tz.newToVTimeZone().toICalendar(writer);
            }
            // VEVENTs/VTODOs
            for (Invite inv : filteredInvs) {
                ZComponent comp = inv.newToVComponent(false, true);
                comp.toICalendar(writer);
            }
            writer.write("END:VCALENDAR\r\n");
        } catch (IOException e) {
            throw ServiceException.FAILURE("Error writing iCalendar", e);
        } finally {
            Closeables.closeQuietly(writer);
        }
        mm.setText(writer.toString());
        ContentType ct = new ContentType(MimeConstants.CT_TEXT_CALENDAR);
        ct.setParameter(MimeConstants.P_CHARSET, MimeConstants.P_CHARSET_UTF8);
        ct.setParameter("method", method);
        mm.setHeader("Content-Type", ct.toString());
    } catch (MessagingException e) {
        ZimbraLog.calendar.warn("Unable to compose email for invite forwarding", e);
    }
    return mm;
}
Also used : Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Mime(com.zimbra.cs.mime.Mime) ZComponent(com.zimbra.common.calendar.ZCalendar.ZComponent) StringWriter(java.io.StringWriter) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZProperty(com.zimbra.common.calendar.ZCalendar.ZProperty) TimeZoneMap(com.zimbra.common.calendar.TimeZoneMap) ICalTimeZone(com.zimbra.common.calendar.ICalTimeZone)

Example 20 with AddressException

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

the class SendShareNotification method generateShareNotification.

protected MimeMessage generateShareNotification(Account authAccount, Account ownerAccount, ShareInfoData sid, String notes, Action action, Collection<String> internlaRecipients, String externalRecipient) throws ServiceException, MessagingException {
    Locale locale = authAccount.getLocale();
    String charset = authAccount.getAttr(Provisioning.A_zimbraPrefMailDefaultCharset, MimeConstants.P_CHARSET_UTF8);
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(authAccount));
    MsgKey subjectKey;
    if (action == null) {
        subjectKey = MsgKey.shareNotifSubject;
    } else {
        switch(action) {
            case edit:
                subjectKey = MsgKey.shareModifySubject;
                break;
            case revoke:
                subjectKey = MsgKey.shareRevokeSubject;
                break;
            case expire:
                subjectKey = MsgKey.shareExpireSubject;
                break;
            default:
                subjectKey = MsgKey.shareNotifSubject;
        }
    }
    String subject = L10nUtil.getMessage(subjectKey, locale);
    String ownerAcctDisplayName = ownerAccount.getDisplayName();
    if (ownerAcctDisplayName == null) {
        ownerAcctDisplayName = ownerAccount.getName();
    }
    subject += L10nUtil.getMessage(MsgKey.sharedBySubject, locale, sid.getName(), ownerAcctDisplayName);
    mm.setSubject(subject, CharsetUtil.checkCharset(subject, charset));
    mm.setSentDate(new Date());
    // from the owner
    mm.setFrom(AccountUtil.getFriendlyEmailAddress(ownerAccount));
    // sent by auth account
    mm.setSender(AccountUtil.getFriendlyEmailAddress(authAccount));
    // to the grantee
    if (internlaRecipients != null) {
        assert (externalRecipient == null);
        for (String recipient : internlaRecipients) {
            try {
                mm.addRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(recipient));
            } catch (AddressException e) {
                sLog.warn("Ignoring error while sending share notification to " + recipient, e);
            }
        }
    } else if (externalRecipient != null) {
        mm.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(externalRecipient));
    } else {
        String recipient = sid.getGranteeName();
        mm.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(recipient));
    }
    MimeMultipart mmp = ShareInfo.NotificationSender.genNotifBody(sid, notes, locale, action, externalRecipient);
    mm.setContent(mmp);
    mm.saveChanges();
    if (sLog.isDebugEnabled()) {
        // log4j.logger.com.zimbra.cs.service.mail=DEBUG
        try {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            mm.writeTo(buf);
            String mmDump = new String(buf.toByteArray());
            sLog.debug("********\n" + mmDump);
        } catch (MessagingException e) {
            sLog.debug("failed log debug share notification message", e);
        } catch (IOException e) {
            sLog.debug("failed log debug share notification message", e);
        }
    }
    return mm;
}
Also used : Locale(java.util.Locale) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) MsgKey(com.zimbra.common.util.L10nUtil.MsgKey) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Date(java.util.Date)

Aggregations

AddressException (javax.mail.internet.AddressException)46 InternetAddress (javax.mail.internet.InternetAddress)37 MimeMessage (javax.mail.internet.MimeMessage)18 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)17 MessagingException (javax.mail.MessagingException)15 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 Date (java.util.Date)7 Address (javax.mail.Address)7 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 Properties (java.util.Properties)4 Session (javax.mail.Session)4 MimeBodyPart (javax.mail.internet.MimeBodyPart)4 ServiceException (com.zimbra.common.service.ServiceException)3 Account (com.zimbra.cs.account.Account)3 Invite (com.zimbra.cs.mailbox.calendar.Invite)3 ZAttendee (com.zimbra.cs.mailbox.calendar.ZAttendee)3 Locale (java.util.Locale)3