Search in sources :

Example 81 with Address

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

the class MailSender method sendMessage.

/** @return a Collection of successfully sent recipient Addresses */
protected Collection<Address> sendMessage(Mailbox mbox, final MimeMessage mm, Collection<RollbackData> rollbacks) throws SafeMessagingException, IOException {
    // send the message via SMTP
    HashSet<Address> sentAddresses = new HashSet<Address>();
    mCurrentHostIndex = 0;
    String hostname = getNextHost();
    try {
        // Initialize recipient addresses
        Address[] rcptAddresses = getRecipients(mm);
        if (rcptAddresses == null || rcptAddresses.length == 0)
            throw new SendFailedException("No recipient addresses");
        while (true) {
            try {
                logMessage(mm, hostname, mOriginalMessageId, mUploads, mReplyType);
                if (hostname != null) {
                    sendMessageToHost(hostname, mm, rcptAddresses);
                } else {
                    Transport.send(mm, rcptAddresses);
                }
                Collections.addAll(sentAddresses, rcptAddresses);
                break;
            } catch (SendFailedException sfe) {
                throw sfe;
            } catch (MessagingException e) {
                Exception chained = e.getNextException();
                if (chained instanceof SocketException || chained instanceof UnknownHostException) {
                    String hostString = (hostname != null ? " " + hostname : "");
                    ZimbraLog.smtp.warn("Unable to connect to SMTP server%s: %s.", hostString, chained.toString());
                    if (mTrackBadHosts) {
                        JMSession.markSmtpHostBad(hostname);
                    }
                    hostname = getNextHost();
                    if (hostname == null) {
                        throw e;
                    }
                    ZimbraLog.smtp.info("Attempting to send to %s.", hostname);
                } else {
                    throw e;
                }
            }
        }
    } catch (SendFailedException e) {
        //skip roll backs for partial send failure cases!
        if (isSendPartial())
            throw new SafeSendFailedException(e);
        for (RollbackData rdata : rollbacks) {
            if (rdata != null) {
                rdata.rollback();
            }
        }
        throw new SafeSendFailedException(e);
    } catch (MessagingException e) {
        for (RollbackData rdata : rollbacks) {
            if (rdata != null) {
                rdata.rollback();
            }
        }
        throw new SafeMessagingException(e);
    } catch (RuntimeException e) {
        for (RollbackData rdata : rollbacks) {
            if (rdata != null) {
                rdata.rollback();
            }
        }
        throw e;
    }
    return sentAddresses;
}
Also used : SocketException(java.net.SocketException) SendFailedException(javax.mail.SendFailedException) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) UnknownHostException(java.net.UnknownHostException) MessagingException(javax.mail.MessagingException) MessagingException(javax.mail.MessagingException) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) SendFailedException(javax.mail.SendFailedException) ServiceException(com.zimbra.common.service.ServiceException) SocketException(java.net.SocketException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) HashSet(java.util.HashSet)

Example 82 with Address

use of javax.mail.Address in project adempiere by adempiere.

the class RequestEMailProcessor method updateRequest.

private boolean updateRequest(int request_upd, Message msg) throws MessagingException, SQLException {
    MRequest requp = new MRequest(getCtx(), request_upd, get_TrxName());
    // Body as result
    Address[] from = msg.getFrom();
    requp.setResult("FROM: " + from[0].toString() + "\n" + getMessage(msg));
    return requp.save();
}
Also used : MRequest(org.compiere.model.MRequest) Address(javax.mail.Address)

Example 83 with Address

use of javax.mail.Address in project adempiere by adempiere.

the class RequestEMailProcessor method dumpEnvelope.

//	getDeliveredReportDetail
/**************************************************************************
	 * 	Print Envelope
	 *	@param m message
	 *	@throws Exception
	 */
private void dumpEnvelope(Message m) throws Exception {
    printOut("-----------------------------------------------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++) printOut("FROM: " + a[j].toString());
    }
    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) printOut("TO: " + a[j].toString());
    }
    // SUBJECT
    printOut("SUBJECT: " + m.getSubject());
    // DATE
    java.util.Date d = m.getSentDate();
    printOut("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    // get the system flags
    Flags.Flag[] sf = flags.getSystemFlags();
    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            // skip it
            continue;
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }
    // get the user flag strings
    String[] uf = flags.getUserFlags();
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    printOut("FLAGS: " + sb.toString());
    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) {
        StringBuffer sb1 = new StringBuffer("X-Mailer: ");
        for (int i = 0; i < hdrs.length; i++) sb1.append(hdrs[i]).append("  ");
        printOut(sb1.toString());
    } else
        printOut("X-Mailer NOT available");
    //	Message ID
    hdrs = m.getHeader("Message-ID");
    if (hdrs != null) {
        StringBuffer sb1 = new StringBuffer("Message-ID: ");
        for (int i = 0; i < hdrs.length; i++) sb1.append(hdrs[i]).append("  ");
        printOut(sb1.toString());
    } else
        printOut("Message-ID NOT available");
    //	All
    printOut("ALL HEADERs:");
    Enumeration en = m.getAllHeaders();
    while (en.hasMoreElements()) {
        Header hdr = (Header) en.nextElement();
        printOut("  " + hdr.getName() + " = " + hdr.getValue());
    }
    printOut("-----------------------------------------------------------------");
}
Also used : Enumeration(java.util.Enumeration) Address(javax.mail.Address) Flags(javax.mail.Flags) Header(javax.mail.Header)

Example 84 with Address

use of javax.mail.Address in project adempiere by adempiere.

the class RequestEMailProcessor method createRequest.

//	processInBox
/**
	 * 	Create request
	 *	@param msg message
	 * @return 
	 *	@return Type of Message
	 * @throws MessagingException 
	 */
private boolean createRequest(Message msg) throws MessagingException, SQLException {
    // Assign from variable
    Address[] from = msg.getFrom();
    String fromAddress;
    // Carlos Ruiz <c_ruiz@myrealbox.com>
    if (from[0].toString().indexOf('<') != -1 && from[0].toString().indexOf('>') != -1) {
        fromAddress = from[0].toString().substring(from[0].toString().indexOf('<') + 1, from[0].toString().indexOf('>'));
        log.info("fromAddress stripped: " + fromAddress);
    } else {
        fromAddress = from[0].toString();
    }
    // Message-ID as documentNo
    String[] hdrs = msg.getHeader("Message-ID");
    // Review if the e-mail was already created, comparing Message-ID+From+body
    int retValuedup = 0;
    String sqldup = "select r_request_id from r_request " + "where ad_client_id = ? " + "and documentno = ? " + "and startdate = ?";
    PreparedStatement pstmtdup = null;
    pstmtdup = DB.prepareStatement(sqldup, null);
    pstmtdup.setInt(1, getAD_Client_ID());
    pstmtdup.setString(2, hdrs[0].substring(0, 30));
    pstmtdup.setTimestamp(3, new Timestamp(msg.getSentDate().getTime()));
    ResultSet rsdup = pstmtdup.executeQuery();
    if (rsdup.next())
        retValuedup = rsdup.getInt(1);
    rsdup.close();
    pstmtdup.close();
    pstmtdup = null;
    if (retValuedup > 0) {
        log.info("request already existed for msg -> " + hdrs[0]);
        return true;
    }
    // Analyze subject if Re: find the original request by subject + e-mail and add an action
    int request_upd = 0;
    String sqlupd = "SELECT r_request_id " + "  FROM r_request " + " WHERE ad_client_id = ? " + "   AND summary LIKE 'FROM: ' || ? || '%' " + "   AND (   documentno = " + "              SUBSTR " + "                 (?, " + "                  INSTR " + "                      (?, " + "                       '<' " + "                      ) " + "                 ) " + "        OR (    ? LIKE 'Re: %' " + "            AND summary = " + "                      'FROM: ' " + "                   || ? " + "                   || CHR (10) " + "                   || SUBSTR (?, 5) " + "           ) " + "       ) ";
    PreparedStatement pstmtupd = null;
    pstmtupd = DB.prepareStatement(sqlupd, null);
    pstmtupd.setInt(1, getAD_Client_ID());
    pstmtupd.setString(2, fromAddress);
    pstmtupd.setString(3, msg.getSubject());
    pstmtupd.setString(4, msg.getSubject());
    pstmtupd.setString(5, msg.getSubject());
    pstmtupd.setString(6, fromAddress);
    pstmtupd.setString(7, msg.getSubject());
    ResultSet rsupd = pstmtupd.executeQuery();
    if (rsupd.next())
        request_upd = rsupd.getInt(1);
    rsupd.close();
    pstmtupd.close();
    pstmtupd = null;
    if (request_upd > 0) {
        log.info("msg -> " + hdrs[0] + " is an answer for req " + request_upd);
        return updateRequest(request_upd, msg);
    }
    MRequest req = new MRequest(getCtx(), 0, get_TrxName());
    // Subject as summary
    req.setSummary("FROM: " + fromAddress + "\n" + msg.getSubject());
    // Body as result
    req.setResult("FROM: " + from[0].toString() + "\n" + getMessage(msg));
    // Message-ID as documentNo
    if (hdrs != null)
        req.setDocumentNo(hdrs[0].substring(0, 30));
    // Default request type for this process
    if (R_RequestType_ID > 0)
        req.setR_RequestType_ID(R_RequestType_ID);
    else
        req.setR_RequestType_ID();
    // set Default sales representative 
    if (SalesRep_ID > 0)
        req.setSalesRep_ID(SalesRep_ID);
    // set Default role
    if (AD_Role_ID > 0)
        req.setAD_Role_ID(AD_Role_ID);
    // Look for user via e-mail
    if (from != null) {
        int retValueu = -1;
        String sqlu = "SELECT ad_user_id " + "  FROM ad_user " + " WHERE UPPER (email) = UPPER (?) " + "   AND ad_client_id = ?";
        PreparedStatement pstmtu = null;
        pstmtu = DB.prepareStatement(sqlu, null);
        pstmtu.setString(1, fromAddress);
        pstmtu.setInt(2, getAD_Client_ID());
        ResultSet rsu = pstmtu.executeQuery();
        if (rsu.next())
            retValueu = rsu.getInt(1);
        rsu.close();
        pstmtu.close();
        pstmtu = null;
        if (retValueu > 0) {
            req.setAD_User_ID(retValueu);
        } else {
            // set default user
            if (AD_User_ID > 0)
                req.setAD_User_ID(AD_User_ID);
        }
    }
    // Look BP
    if (req.getAD_User_ID() > 0) {
        MUser us = new MUser(getCtx(), req.getAD_User_ID(), get_TrxName());
        if (us.getC_BPartner_ID() > 0)
            req.setC_BPartner_ID(us.getC_BPartner_ID());
    }
    if (req.getC_BPartner_ID() <= 0 && C_BPartner_ID > 0) {
        // set default business partner
        req.setC_BPartner_ID(C_BPartner_ID);
    }
    // Set start date as sent date of e-mail
    req.setStartDate(new Timestamp(msg.getSentDate().getTime()));
    // defaults priority Medium, confidentiality partner
    if (p_DefaultConfidentiality != null) {
        req.setConfidentialType(p_DefaultConfidentiality);
        req.setConfidentialTypeEntry(p_DefaultConfidentiality);
    }
    if (p_DefaultPriority != null) {
        req.setPriority(p_DefaultPriority);
        req.setPriorityUser(p_DefaultPriority);
    }
    if (req.save(get_TrxName())) {
        log.info("created request " + req.getR_Request_ID() + " from msg -> " + hdrs[0]);
        // get simple attachments and attach to request
        if (msg.isMimeType("multipart/*")) {
            try {
                Multipart mp = (Multipart) msg.getContent();
                for (int i = 0, n = mp.getCount(); i < n; i++) {
                    Part part = mp.getBodyPart(i);
                    String disposition = part.getDisposition();
                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
                        MAttachment attach = req.createAttachment();
                        InputStream in = part.getInputStream();
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        //1KiB buffer
                        final int BUF_SIZE = 1 << 8;
                        byte[] buffer = new byte[BUF_SIZE];
                        int bytesRead = -1;
                        while ((bytesRead = in.read(buffer)) > -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                        in.close();
                        byte[] bytes = out.toByteArray();
                        attach.addEntry(part.getFileName(), bytes);
                        attach.saveEx(get_TrxName());
                    }
                }
            } catch (IOException e) {
                log.log(Level.FINE, "Error extracting attachments", e);
            }
        }
        return true;
    } else {
        return false;
    }
}
Also used : MRequest(org.compiere.model.MRequest) Multipart(javax.mail.Multipart) MAttachment(org.compiere.model.MAttachment) Address(javax.mail.Address) InputStream(java.io.InputStream) PreparedStatement(java.sql.PreparedStatement) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) Part(javax.mail.Part) ResultSet(java.sql.ResultSet) MUser(org.compiere.model.MUser)

Example 85 with Address

use of javax.mail.Address in project adempiere by adempiere.

the class EMailProcessor method dumpEnvelope.

//	getDeliveredReportDetail
/**************************************************************************
	 * 	Print Envelope
	 *	@param m message
	 *	@throws Exception
	 */
private void dumpEnvelope(Message m) throws Exception {
    printOut("-----------------------------------------------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++) printOut("FROM: " + a[j].toString());
    }
    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) printOut("TO: " + a[j].toString());
    }
    // SUBJECT
    printOut("SUBJECT: " + m.getSubject());
    // DATE
    java.util.Date d = m.getSentDate();
    printOut("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    // get the system flags
    Flags.Flag[] sf = flags.getSystemFlags();
    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            // skip it
            continue;
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }
    // get the user flag strings
    String[] uf = flags.getUserFlags();
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    printOut("FLAGS: " + sb.toString());
    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) {
        StringBuffer sb1 = new StringBuffer("X-Mailer: ");
        for (int i = 0; i < hdrs.length; i++) sb1.append(hdrs[i]).append("  ");
        printOut(sb1.toString());
    } else
        printOut("X-Mailer NOT available");
    //	Message ID
    hdrs = m.getHeader("Message-ID");
    if (hdrs != null) {
        StringBuffer sb1 = new StringBuffer("Message-ID: ");
        for (int i = 0; i < hdrs.length; i++) sb1.append(hdrs[i]).append("  ");
        printOut(sb1.toString());
    } else
        printOut("Message-ID NOT available");
    //	All
    printOut("ALL HEADERs:");
    Enumeration en = m.getAllHeaders();
    while (en.hasMoreElements()) {
        Header hdr = (Header) en.nextElement();
        printOut("  " + hdr.getName() + " = " + hdr.getValue());
    }
    printOut("-----------------------------------------------------------------");
}
Also used : Enumeration(java.util.Enumeration) Address(javax.mail.Address) Flags(javax.mail.Flags) Header(javax.mail.Header)

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