Search in sources :

Example 66 with Address

use of javax.mail.Address in project ACS by ACS-Community.

the class ACSMailAndSmsServer method sendEmail.

/**
	 * Send and email.
	 * 
	 * @param address The address to send the email to
	 * @param subject The subject of the email
	 * @param text The text of the email
	 * 
	 * @see cern.laser.business.pojo.MailAndSmsServerImpl
	 */
public void sendEmail(final String address, final String subject, final String text) {
    if (address == null || address.isEmpty()) {
        logger.log(AcsLogLevel.WARNING, "Sending EMAIL aborted: no valid dest. address");
    }
    logger.log(AcsLogLevel.DEBUG, "Sending EMAIL to " + address + ", subject=" + subject);
    Thread MailerThread = new Thread(new Runnable() {

        public void run() {
            try {
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom();
                if (address.contains(";")) {
                    String[] addresses = address.split(";");
                    Vector<Address> addressesVector = new Vector<Address>();
                    for (String toAddress : addresses) {
                        if (!toAddress.trim().isEmpty()) {
                            addressesVector.add(new InternetAddress(toAddress.trim()));
                        }
                    }
                    Address[] addrrs = new Address[addressesVector.size()];
                    addressesVector.toArray(addrrs);
                    msg.setRecipients(Message.RecipientType.TO, addrrs);
                } else {
                    msg.setRecipients(Message.RecipientType.TO, address);
                }
                msg.setSubject(subject);
                msg.setSentDate(new Date());
                msg.setText(text);
                Transport.send(msg);
                logger.log(AcsLogLevel.DEBUG, "Email sent");
            } catch (MessagingException mex) {
                logger.log(AcsLogLevel.ERROR, "Error sending email " + mex.toString());
            }
        }
    }, "MailerThread_" + System.currentTimeMillis());
    MailerThread.setDaemon(true);
    MailerThread.start();
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Vector(java.util.Vector) Date(java.util.Date)

Example 67 with Address

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

the class CalendarRequest method sendCalendarMessageInternal.

/**
     * Send an iCalendar email message and optionally create/update/cancel
     * corresponding appointment/invite in sender's calendar.
     * @param zsc
     * @param apptFolderId
     * @param acct
     * @param mbox
     * @param csd
     * @param response
     * @param updateOwnAppointment if true, corresponding change is made to
     *                             sender's calendar
     * @return
     * @throws ServiceException
     */
private static Element sendCalendarMessageInternal(ZimbraSoapContext zsc, OperationContext octxt, int apptFolderId, Account acct, Mailbox mbox, CalSendData csd, Element response, boolean updateOwnAppointment, boolean forceSend, MailSendQueue sendQueue) throws ServiceException {
    boolean onBehalfOf = isOnBehalfOfRequest(zsc);
    boolean notifyOwner = onBehalfOf && acct.getBooleanAttr(Provisioning.A_zimbraPrefCalendarNotifyDelegatedChanges, false);
    if (notifyOwner) {
        try {
            InternetAddress addr = AccountUtil.getFriendlyEmailAddress(acct);
            csd.mMm.addRecipient(javax.mail.Message.RecipientType.TO, addr);
        } catch (MessagingException e) {
            throw ServiceException.FAILURE("count not add calendar owner to recipient list", e);
        }
    }
    // in a non-delegated request.
    if (!onBehalfOf) {
        String[] aliases = acct.getMailAlias();
        String[] addrs;
        if (aliases != null && aliases.length > 0) {
            addrs = new String[aliases.length + 1];
            addrs[0] = acct.getAttr(Provisioning.A_mail);
            for (int i = 0; i < aliases.length; i++) {
                addrs[i + 1] = aliases[i];
            }
        } else {
            addrs = new String[1];
            addrs[0] = acct.getAttr(Provisioning.A_mail);
        }
        try {
            Mime.removeRecipients(csd.mMm, addrs);
        } catch (MessagingException e) {
        }
    }
    ParsedMessage pm = new ParsedMessage(csd.mMm, false);
    if (csd.mInvite.getFragment() == null || csd.mInvite.getFragment().equals("")) {
        csd.mInvite.setFragment(pm.getFragment(acct.getLocale()));
    }
    boolean willNotify = false;
    if (!csd.mDontNotifyAttendees) {
        try {
            Address[] rcpts = csd.mMm.getAllRecipients();
            willNotify = rcpts != null && rcpts.length > 0;
        } catch (MessagingException e) {
            throw ServiceException.FAILURE("Checking recipients of outgoing msg ", e);
        }
    }
    // Validate the addresses first.
    if (!csd.mInvite.isCancel() && !forceSend && willNotify) {
        try {
            MailUtil.validateRcptAddresses(JMSession.getSmtpSession(mbox.getAccount()), csd.mMm.getAllRecipients());
        } catch (MessagingException mex) {
            if (mex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) mex;
                throw MailServiceException.SEND_ABORTED_ADDRESS_FAILURE("invalid addresses", sfex, sfex.getInvalidAddresses(), sfex.getValidUnsentAddresses());
            }
        }
    }
    AddInviteData aid = null;
    File tempMmFile = null;
    boolean queued = false;
    try {
        if (willNotify) {
            // Write out the MimeMessage to a temp file and create a new MimeMessage from the file.
            // If we don't do this, we get into trouble during modify appointment call.  If the blob
            // is bigger than the streaming threshold (e.g. appointment has a big attachment), the
            // MimeMessage object is attached to the current blob file.  But the Mailbox.addInvite()
            // call below updates the blob to a new mod_content (hence new path).  The attached blob
            // thus having been deleted, the MainSender.sendMimeMessage() call that follows will attempt
            // to read from a non-existent file and fail.  We can avoid this situation by writing the
            // to-be-emailed mime message to a temp file, thus detaching it from the appointment's
            // current blob file.  This is inefficient, but safe.
            OutputStream os = null;
            InputStream is = null;
            try {
                tempMmFile = File.createTempFile("zcal", "tmp");
                os = new FileOutputStream(tempMmFile);
                csd.mMm.writeTo(os);
                ByteUtil.closeStream(os);
                os = null;
                is = new ZSharedFileInputStream(tempMmFile);
                csd.mMm = new FixedMimeMessage(JMSession.getSmtpSession(acct), is);
            } catch (IOException e) {
                if (tempMmFile != null)
                    tempMmFile.delete();
                throw ServiceException.FAILURE("error creating calendar message content", e);
            } catch (MessagingException e) {
                if (tempMmFile != null)
                    tempMmFile.delete();
                throw ServiceException.FAILURE("error creating calendar message content", e);
            } finally {
                ByteUtil.closeStream(os);
                ByteUtil.closeStream(is);
            }
        }
        // because email send will delete uploaded attachments as a side-effect.
        if (updateOwnAppointment) {
            aid = mbox.addInvite(octxt, csd.mInvite, apptFolderId, pm);
        }
        // Next, notify any attendees.
        if (willNotify) {
            MailSendQueueEntry entry = new MailSendQueueEntry(octxt, mbox, csd, tempMmFile);
            sendQueue.add(entry);
            queued = true;
        }
    } finally {
        // Delete the temp file if it wasn't queued.
        if (tempMmFile != null && !queued) {
            tempMmFile.delete();
        }
    }
    if (updateOwnAppointment && response != null && aid != null) {
        csd.mAddInvData = aid;
        ItemIdFormatter ifmt = new ItemIdFormatter(zsc);
        String id = ifmt.formatItemId(aid.calItemId);
        response.addAttribute(MailConstants.A_CAL_ID, id);
        if (csd.mInvite.isEvent())
            // for backward compat
            response.addAttribute(MailConstants.A_APPT_ID_DEPRECATE_ME, id);
        response.addAttribute(MailConstants.A_CAL_INV_ID, ifmt.formatItemId(aid.calItemId, aid.invId));
        if (Invite.isOrganizerMethod(csd.mInvite.getMethod())) {
            response.addAttribute(MailConstants.A_MODIFIED_SEQUENCE, aid.modSeq);
            response.addAttribute(MailConstants.A_REVISION, aid.rev);
        }
    }
    return response;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) ItemIdFormatter(com.zimbra.cs.service.util.ItemIdFormatter) ParsedMessage(com.zimbra.cs.mime.ParsedMessage) AddInviteData(com.zimbra.cs.mailbox.Mailbox.AddInviteData) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FixedMimeMessage(com.zimbra.cs.mime.Mime.FixedMimeMessage) IOException(java.io.IOException) ZSharedFileInputStream(com.zimbra.common.zmime.ZSharedFileInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 68 with Address

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

the class CalendarRequest method sendOrganizerChangeMessage.

protected static void sendOrganizerChangeMessage(ZimbraSoapContext zsc, OperationContext octxt, CalendarItem calItem, Account acct, Mailbox mbox, MailSendQueue sendQueue) {
    try {
        Account authAccount = getAuthenticatedAccount(zsc);
        Invite[] invites = calItem.getInvites();
        for (Invite inv : invites) {
            List<Address> rcpts = CalendarMailSender.toListFromAttendees(inv.getAttendees());
            if (rcpts.size() > 0) {
                CalSendData csd = new CalSendData();
                csd.mInvite = inv;
                csd.mOrigId = new ItemId(mbox, inv.getMailItemId());
                csd.mMm = CalendarMailSender.createOrganizerChangeMessage(acct, authAccount, zsc.isUsingAdminPrivileges(), calItem, csd.mInvite, rcpts);
                sendCalendarMessageInternal(zsc, octxt, calItem.getFolderId(), acct, mbox, csd, null, false, true, sendQueue);
            }
        }
    } catch (ServiceException e) {
        ZimbraLog.calendar.warn("Ignoring error while sending organizer change message", e);
    }
}
Also used : Account(com.zimbra.cs.account.Account) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) ItemId(com.zimbra.cs.service.util.ItemId) Invite(com.zimbra.cs.mailbox.calendar.Invite)

Example 69 with Address

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

the class CancelCalendarItem method cancelInstance.

void cancelInstance(ZimbraSoapContext zsc, OperationContext octxt, Element msgElem, Account acct, Mailbox mbox, CalendarItem calItem, Invite inv, RecurId recurId, List<ZAttendee> toNotify, MailSendQueue sendQueue) throws ServiceException {
    boolean onBehalfOf = isOnBehalfOfRequest(zsc);
    Account authAcct = getAuthenticatedAccount(zsc);
    Locale locale = !onBehalfOf ? acct.getLocale() : authAcct.getLocale();
    String text = L10nUtil.getMessage(MsgKey.calendarCancelAppointmentInstance, locale);
    Invite cancelInvite = CalendarUtils.buildCancelInstanceCalendar(acct, authAcct, zsc.isUsingAdminPrivileges(), onBehalfOf, calItem, inv, text, recurId);
    CalSendData dat = new CalSendData();
    dat.mOrigId = new ItemId(mbox, inv.getMailItemId());
    dat.mReplyType = MailSender.MSGTYPE_REPLY;
    dat.mInvite = cancelInvite;
    ZVCalendar iCal = dat.mInvite.newToICalendar(true);
    // did they specify a custom <m> message?  If so, then we don't have to build one...
    if (msgElem != null) {
        String desc = ParseMimeMessage.getTextPlainContent(msgElem);
        String html = ParseMimeMessage.getTextHtmlContent(msgElem);
        iCal.addDescription(desc, html);
        MimeBodyPart[] mbps = new MimeBodyPart[1];
        mbps[0] = CalendarMailSender.makeICalIntoMimePart(iCal);
        // the <inv> element is *NOT* allowed -- we always build it manually
        // based on the params to the <CancelCalendarItem> and stick it in the
        // mbps (additionalParts) parameter...
        dat.mMm = ParseMimeMessage.parseMimeMsgSoap(zsc, octxt, mbox, msgElem, mbps, ParseMimeMessage.NO_INV_ALLOWED_PARSER, dat);
    } else {
        List<Address> rcpts = CalendarMailSender.toListFromAttendees(toNotify);
        dat.mMm = CalendarMailSender.createCancelMessage(acct, authAcct, zsc.isUsingAdminPrivileges(), onBehalfOf, rcpts, calItem, cancelInvite, text, iCal);
    }
    doRecipientsCheck(dat, inv.isOrganizer(), mbox);
    sendCalendarCancelMessage(zsc, octxt, calItem.getFolderId(), acct, mbox, dat, true, sendQueue);
}
Also used : Locale(java.util.Locale) Account(com.zimbra.cs.account.Account) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) Address(javax.mail.Address) MimeBodyPart(javax.mail.internet.MimeBodyPart) ItemId(com.zimbra.cs.service.util.ItemId) Invite(com.zimbra.cs.mailbox.calendar.Invite)

Example 70 with Address

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

the class CancelCalendarItem method cancelInvite.

protected void cancelInvite(ZimbraSoapContext zsc, OperationContext octxt, Element msgElem, Account acct, Mailbox mbox, CalendarItem calItem, Invite inv, MailSendQueue sendQueue) throws ServiceException {
    boolean onBehalfOf = isOnBehalfOfRequest(zsc);
    Account authAcct = getAuthenticatedAccount(zsc);
    Locale locale = !onBehalfOf ? acct.getLocale() : authAcct.getLocale();
    String text = L10nUtil.getMessage(MsgKey.calendarCancelAppointment, locale);
    CalSendData csd = new CalSendData();
    csd.mOrigId = new ItemId(mbox, inv.getMailItemId());
    csd.mReplyType = MailSender.MSGTYPE_REPLY;
    csd.mInvite = CalendarUtils.buildCancelInviteCalendar(acct, authAcct, zsc.isUsingAdminPrivileges(), onBehalfOf, calItem, inv, text);
    ZVCalendar iCal = csd.mInvite.newToICalendar(true);
    // did they specify a custom <m> message?  If so, then we don't have to build one...
    if (msgElem != null) {
        String desc = ParseMimeMessage.getTextPlainContent(msgElem);
        String html = ParseMimeMessage.getTextHtmlContent(msgElem);
        iCal.addDescription(desc, html);
        MimeBodyPart[] mbps = new MimeBodyPart[1];
        mbps[0] = CalendarMailSender.makeICalIntoMimePart(iCal);
        // the <inv> element is *NOT* allowed -- we always build it manually
        // based on the params to the <CancelCalendarItem> and stick it in the
        // mbps (additionalParts) parameter...
        csd.mMm = ParseMimeMessage.parseMimeMsgSoap(zsc, octxt, mbox, msgElem, mbps, ParseMimeMessage.NO_INV_ALLOWED_PARSER, csd);
    } else {
        List<Address> rcpts;
        if (inv.isOrganizer())
            rcpts = CalendarMailSender.toListFromAttendees(inv.getAttendees());
        else
            rcpts = new ArrayList<Address>(0);
        csd.mMm = CalendarMailSender.createCancelMessage(acct, authAcct, zsc.isUsingAdminPrivileges(), onBehalfOf, rcpts, calItem, inv, text, iCal);
    }
    doRecipientsCheck(csd, inv.isOrganizer(), mbox);
    sendCalendarCancelMessage(zsc, octxt, calItem.getFolderId(), acct, mbox, csd, true, sendQueue);
}
Also used : Locale(java.util.Locale) Account(com.zimbra.cs.account.Account) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) Address(javax.mail.Address) ArrayList(java.util.ArrayList) MimeBodyPart(javax.mail.internet.MimeBodyPart) ItemId(com.zimbra.cs.service.util.ItemId)

Aggregations

Address (javax.mail.Address)89 InternetAddress (javax.mail.internet.InternetAddress)69 MessagingException (javax.mail.MessagingException)35 MimeMessage (javax.mail.internet.MimeMessage)34 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)21 ArrayList (java.util.ArrayList)20 Date (java.util.Date)19 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 Account (com.zimbra.cs.account.Account)12 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)10 IOException (java.io.IOException)9 Locale (java.util.Locale)9 Message (javax.mail.Message)9 ItemId (com.zimbra.cs.service.util.ItemId)8 Header (javax.mail.Header)8 NHINDAddress (org.nhindirect.stagent.NHINDAddress)8 AddressException (javax.mail.internet.AddressException)7 MimeMultipart (javax.mail.internet.MimeMultipart)7 ZVCalendar (com.zimbra.common.calendar.ZCalendar.ZVCalendar)6 Invite (com.zimbra.cs.mailbox.calendar.Invite)6