Example usage for javax.mail.internet InternetAddress getAddress

List of usage examples for javax.mail.internet InternetAddress getAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getAddress.

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

From source file:mitm.application.djigzo.james.mailets.SMIMESign.java

private KeyAndCertificate getSigningKeyAndCertificateAction(Session session, InternetAddress originator)
        throws DatabaseException {
    KeyAndCertificate keyAndCertificate = null;

    if (originator != null) {
        try {/*from   ww w.jav a2  s.c o  m*/
            User user;

            try {
                String userEmail = originator.getAddress();

                userEmail = EmailAddressUtils.canonicalizeAndValidate(userEmail, false);

                user = userWorkflow.getUser(userEmail, UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);
            } catch (HierarchicalPropertiesException e) {
                throw new DatabaseException(e);
            }

            keyAndCertificate = user.getSigningKeyAndCertificate();

            if (keyAndCertificate != null) {
                makePersistent(user);
            }
        } catch (CertStoreException e) {
            throw new DatabaseException(e);
        } catch (KeyStoreException e) {
            throw new DatabaseException(e);
        } catch (AddressException e) {
            throw new DatabaseException(e);
        } catch (HierarchicalPropertiesException e) {
            throw new DatabaseException(e);
        }
    }

    return keyAndCertificate;
}

From source file:com.stimulus.archiva.domain.Email.java

protected String getAddresses(Address[] recipients, DisplayMode displayMode) {
    if (recipients == null)
        return "";
    StringBuffer result = new StringBuffer();

    for (int i = 0; i < recipients.length; i++) {
        if (recipients[i] instanceof InternetAddress) {
            InternetAddress address = (InternetAddress) recipients[i];
            switch (displayMode) {
            case ALL:
                if (address.getPersonal() != null)
                    result.append(address.getPersonal());
                result.append(" <");
                result.append(DecodingUtil.decodeWord(address.getAddress()));
                result.append(">");
                break;
            case EMAIL_ONLY:
                result.append(DecodingUtil.decodeWord(address.getAddress()));
                break;
            case NAME_ONLY:
                if (address.getPersonal() != null)
                    result.append(DecodingUtil.decodeWord(address.getPersonal()));
                else
                    result.append(DecodingUtil.decodeWord(address.getAddress()));
                break;
            }/*  w ww . j  a  va2  s. c o m*/
        } else if (recipients[i] instanceof NewsAddress) {
            result.append("newsgroup:");
            result.append(((NewsAddress) recipients[i]).getNewsgroup());

        } else
            result.append(DecodingUtil.decodeWord(recipients[i].toString()));
        if (i < recipients.length - 1)
            result.append(", ");
    }
    return result.toString().trim();
}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error/*from w  w w  . ja v  a  2 s.c o  m*/
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);

    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);

    if (log.isDebugEnabled()) {
        log.debug(
                "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }

    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }

    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress()
                    + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress()
                        + " from transport configuration");
            }
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses)
                    + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)
                    + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    //TODO: use a combined message id for smtp so that it generates a unique id while
    // being able to support asynchronous communication.
    // if a custom message id is set, use it
    //        if (msgContext.getMessageID() != null) {
    //            message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
    //            message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    //        }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }

    DataHandler dataHandler = new DataHandler(
            messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));

    MimeMultipart mimeMultiPart = null;

    String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
    if (mFormat == null) {
        mFormat = defaultMailFormat;
    }

    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }

    MimePart mainPart;
    if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        mainPart = mimeBodyPart2;
    } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);

        String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
        if (fileName != null) {
            mimeBodyPart2.setFileName(fileName);
        } else {
            mimeBodyPart2.setFileName("attachment");
        }

        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }

    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);

        // AXIOM's idea of what is textual also includes application/xml and
        // application/soap+xml (which JavaMail considers as binary). For these content types
        // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter
        // here because it can choose between 7bit and quoted-printable automatically, but it
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding",
                    (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }

        //setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions()
                    .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }

        log.debug("Sending message");
        Transport.send(message);

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }

    } catch (MessagingException e) {
        metrics.incrementFaultsSending();
        handleException("Error creating mail message or sending it to the configured server", e);

    }
    return message.getMessageID();
}

From source file:immf.SendMailBridge.java

/**
 * SMTP???????// www  .ja v  a2s .c  om
 * @param msg
 * @throws IOException
 */
public void receiveMail(MyWiserMessage msg) throws IOException {
    try {
        SenderMail senderMail = new SenderMail();

        log.info("==== SMTP???????====");
        log.info("From       " + msg.getEnvelopeSender());
        log.info("Recipients  " + msg.getEnvelopeReceiver());

        MimeMessage mime = msg.getMimeMessage();

        String messageId = mime.getHeader("Message-ID", null);
        log.info("messageID  " + messageId);
        List<String> recipients;
        if (messageId != null && receivedMessageTable != null) {
            synchronized (receivedMessageTable) {
                recipients = receivedMessageTable.get(messageId);
                if (recipients != null) {
                    recipients.addAll(msg.getEnvelopeReceiver());
                    log.info("Duplicated message ignored");
                    return;
                }

                recipients = msg.getEnvelopeReceiver();
                receivedMessageTable.put(messageId, recipients);
                receivedMessageTable.wait(this.duplicationCheckTimeSec * 1000);
                receivedMessageTable.remove(messageId);
            }
        } else {
            recipients = msg.getEnvelopeReceiver();
        }

        List<InternetAddress> to = getRecipients(mime, "To");
        List<InternetAddress> cc = getRecipients(mime, "Cc");
        List<InternetAddress> bcc = getBccRecipients(recipients, to, cc);

        int maxRecipients = MaxRecipient;
        if (this.alwaysBcc != null) {
            log.debug("add alwaysbcc " + this.alwaysBcc);
            bcc.add(new InternetAddress(this.alwaysBcc));
        }
        log.info("To   " + StringUtils.join(to, " / "));
        log.info("cc   " + StringUtils.join(cc, " / "));
        log.info("bcc   " + StringUtils.join(bcc, " / "));

        senderMail.setTo(to);
        senderMail.setCc(cc);
        senderMail.setBcc(bcc);

        if (maxRecipients < (to.size() + cc.size() + bcc.size())) {
            log.warn("??????i.net???5??");
            throw new IOException("Too Much Recipients");
        }

        String contentType = mime.getContentType().toLowerCase();
        log.info("ContentType:" + contentType);

        String charset = (new ContentType(contentType)).getParameter("charset");
        log.info("charset:" + charset);

        String mailer = mime.getHeader("X-Mailer", null);
        log.info("mailer  " + mailer);

        String subject = mime.getHeader("Subject", null);
        log.info("subject  " + subject);
        if (subject != null)
            subject = this.charConv.convertSubject(subject);
        log.debug(" conv " + subject);

        if (this.useGoomojiSubject) {
            String goomojiSubject = mime.getHeader("X-Goomoji-Subject", null);
            if (goomojiSubject != null)
                subject = this.googleCharConv.convertSubject(goomojiSubject);
        }

        boolean editRe = false;
        if (this.editDocomoSubjectPrefix) {
            for (InternetAddress addr : to) {
                String[] toString = addr.getAddress().split("@", 2);
                if (subject != null && toString[1].equals("docomo.ne.jp")) {
                    editRe = true;
                }
            }
        }
        if (editRe) {
            if (subject.matches("^R[eE]: ?R[eE].*$")) {
                log.info("?subject: " + subject);
                String reCounterStr = subject.replaceAll("^R[eE]: ?R[eE](\\d*):.*$", "$1");
                int reCounter = 2;
                if (!reCounterStr.isEmpty()) {
                    reCounter = Integer.parseInt(reCounterStr);
                    reCounter++;
                }
                subject = subject.replaceAll("^R[eE]: ?R[eE]\\d*:", "Re" + Integer.toString(reCounter) + ":");
                log.info("subject: " + subject);
            }
        }

        senderMail.setSubject(subject);

        Object content = mime.getContent();
        if (content instanceof String) {
            // 
            String strContent = (String) content;
            if (contentType.toLowerCase().startsWith("text/html")) {
                log.info("Single html part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setHtmlContent(strContent);
            } else {
                log.info("Single plainText part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setPlainTextContent(strContent);
            }
        } else if (content instanceof Multipart) {
            Multipart mp = (Multipart) content;
            parseMultipart(senderMail, mp, getSubtype(contentType), null);
            if (senderMail.getHtmlContent() == null && senderMail.getHtmlWorkingContent() != null) {
                senderMail.setHtmlContent(senderMail.getHtmlWorkingContent());
            }

        } else {
            log.warn("? " + content.getClass().getName());
            throw new IOException("Unsupported type " + content.getClass().getName() + ".");
        }

        if (stripAppleQuote) {
            Util.stripAppleQuotedLines(senderMail);
        }
        Util.stripLastEmptyLines(senderMail);

        log.info("Content  " + mime.getContent());
        log.info("====");

        if (this.sendAsync) {
            // ??
            // ?????OK?
            this.picker.add(senderMail);
        } else {
            // ??????
            this.client.sendMail(senderMail, this.forcePlainText);
            if (isForwardSent) {
                status.setNeedConnect();
            }
        }

    } catch (IOException e) {
        log.warn("Bad Mail Received.", e);
        throw e;
    } catch (Exception e) {
        log.error("ReceiveMail Error.", e);
        throw new IOException("ReceiveMail Error." + e.getMessage(), e);
    }
}

From source file:immf.AppNotifications.java

public void run() {
    boolean authOk = false;
    if (this.credentials.isEmpty()) {
        if (!this.auth()) {
            log.warn(/*w  w  w.jav a 2s  . c o  m*/
                    "???????????");
            return;
        }
        authOk = true;
        log.info("credentials??push???");
    } else {
        log.info("push???");
    }
    if (dnsCache) {
        log.info(
                "DNS??(SSL????????????)");
    }
    int c = 0;
    while (true) {
        try {
            Thread.sleep(ReconnectInterval);
        } catch (Exception e) {
        }

        // ?????5
        if (this.sendMailQueue.size() > 0 && c++ > ReconnectCount) {
            log.info("push");

        } else if (this.recieveMailQueue.size() > newmails) {
            log.warn("");

        } else if (newmails == 0) {
            continue;

        } else if (this.recieveMailQueue.size() < newmails) {
            // ???????
            if (c++ > 100) {
                log.warn("?");
                newmails = this.recieveMailQueue.size();
            }
            continue;
        }
        c = 0;

        synchronized (this.recieveMailQueue) {
            for (int i = this.recieveMailQueue.size(); i > 0; i--) {
                this.sendMailQueue.add(this.recieveMailQueue.remove());
            }
            newmails = 0;
        }

        // push
        int count = this.sendMailQueue.size();
        ImodeMail mail = this.sendMailQueue.peek();
        String pushMessage = this.message;
        String pushCommand = "";

        if (!this.pushFromInfo) {
            pushMessage += "(" + Integer.toString(count) + ")";
        }
        String delimiter = "";
        if (!pushMessage.isEmpty()) {
            delimiter = "\n";
        }
        if (mail != null && this.pushSubjectInfo) {
            String subject = mail.getSubject();
            if (subject.isEmpty()) {
                subject = "(????)";
            }
            pushMessage += delimiter + subject;
            delimiter = " ";
        }
        if (mail != null && this.pushFromInfo) {
            InternetAddress fromAddr = mail.getFromAddr();
            String from = fromAddr.getPersonal();
            if (from == null || from.isEmpty()) {
                from = fromAddr.getAddress();
            }
            if (count == 1) {
                pushMessage += delimiter + "(" + from + ")";
            } else {
                pushMessage += delimiter + "(" + from + "," + Integer.toString(count - 1) + ")";
            }
        }
        if (mail != null && this.pushReplyButton) {
            // (%20)??+???????
            InternetAddress fromAddr = mail.getFromAddr();
            pushCommand = "mailto:" + fromAddr.getAddress();
            for (InternetAddress to : mail.getToAddrList()) {
                pushCommand += "%2C" + to.getAddress();
            }
            String ccList = "";
            for (InternetAddress cc : mail.getCcAddrList()) {
                if (ccList.isEmpty()) {
                    ccList = "?cc=" + cc.getAddress();
                } else {
                    ccList += "%2C" + cc.getAddress();
                }
            }
            if (!ccList.isEmpty()) {
                pushCommand += ccList;
                //pushCommand += "&subject=";
                //}else{
                //pushCommand += "?subject=";
            }
            /* 
             * XXX
             * Apple URL Scheme Reference?? RFC2368 ?????????
             * 8bit?? subject ???? RFC2047 ??????
             * ??????8bit??? Push ???
             * Push ????????
             */
        }
        try {
            log.info("push:" + pushMessage.replace("\n", "/"));
            if (this.pushReplyButton) {
                this.send(pushMessage, pushCommand);
            } else {
                this.send(pushMessage);
            }
            authOk = true;
            this.sendMailQueue.clear();

        } catch (SocketException se) {
            // 
            log.warn("?push????", se);

        } catch (ClientProtocolException cpe) {
            // 
            log.warn("?push????", cpe);

        } catch (UnknownHostException uhe) {
            // DNS
            log.warn("DNS?push????", uhe);

        } catch (SSLException ssle) {
            // SSL
            log.warn("SSL?push????", ssle);

        } catch (MyHttpException mhe) {
            // 
            log.warn("??push????", mhe);

        } catch (Exception e) {
            log.warn("push???", e);
            if (authOk) {
                continue;
            }

            // ????????????????
            this.credentials = "";

            // status.ini???credentials???????????
            if (this.auth()) {
                authOk = true;
                log.info("credentials???");
                try {
                    log.info("push:" + pushMessage.replace("\n", "/"));
                    if (this.pushReplyButton) {
                        this.send(pushMessage, pushCommand);
                    } else {
                        this.send(pushMessage);
                    }
                    this.sendMailQueue.clear();

                } catch (Exception ex) {
                    log.warn("pushpush????", e);
                    this.setCredentials("");
                    this.sendMailQueue.clear();
                    return;
                }
            } else {
                log.warn("??push????");
                this.setCredentials("");
                this.sendMailQueue.clear();
                return;
            }
        }
    }
}

From source file:org.silverpeas.core.importexport.control.RepositoriesTypeManager.java

private void processMailContent(PublicationDetail pubDetail, File file, ImportReportManager reportManager,
        UnitReport unitReport, GEDImportExport gedIE, boolean isVersioningUsed) throws ImportExportException {

    String componentId = gedIE.getCurrentComponentId();
    UserDetail userDetail = gedIE.getCurrentUserDetail();
    MailExtractor extractor = null;/*from w ww . ja v a 2 s  .c o  m*/
    Mail mail = null;
    try {
        extractor = Extractor.getExtractor(file);
        mail = extractor.getMail();
    } catch (Exception e) {
        SilverLogger.getLogger(this).error("Cannot extract mail data", e);
    }
    if (mail != null) {
        // save mail data into dedicated form
        String content = mail.getBody();
        PublicationContentType pubContent = new PublicationContentType();
        XMLModelContentType modelContent = new XMLModelContentType("mail");
        pubContent.setXMLModelContentType(modelContent);
        List<XMLField> fields = new ArrayList<>();
        modelContent.setFields(fields);

        XMLField subject = new XMLField("subject", mail.getSubject());
        fields.add(subject);

        XMLField body = new XMLField("body", ESCAPE_ISO8859_1.translate(content));
        fields.add(body);

        XMLField date = new XMLField("date", DateUtil.getOutputDateAndHour(mail.getDate(), "fr"));
        fields.add(date);

        InternetAddress address = mail.getFrom();
        String from = "";
        if (StringUtil.isDefined(address.getPersonal())) {
            from += address.getPersonal() + " - ";
        }
        from += "<a href=\"mailto:" + address.getAddress() + "\">" + address.getAddress() + "</a>";
        XMLField fieldFROM = new XMLField("from", from);
        fields.add(fieldFROM);

        Address[] recipients = mail.getAllRecipients();
        StringBuilder to = new StringBuilder();
        for (Address recipient : recipients) {
            InternetAddress ia = (InternetAddress) recipient;
            if (StringUtil.isDefined(ia.getPersonal())) {
                to.append(ia.getPersonal()).append(" - ");
            }
            to.append("<a href=\"mailto:").append(ia.getAddress()).append("\">").append(ia.getAddress())
                    .append("</a></br>");
        }
        XMLField fieldTO = new XMLField("to", to.toString());
        fields.add(fieldTO);

        // save form
        gedIE.createPublicationContent(reportManager, unitReport, Integer.parseInt(pubDetail.getPK().getId()),
                pubContent, userDetail.getId(), null);

        try {
            // extract each file from mail...
            List<AttachmentDetail> documents = extractAttachmentsFromMail(componentId, userDetail, extractor);
            // ... and save them
            saveAttachments(componentId, pubDetail, documents, userDetail, gedIE, isVersioningUsed);
        } catch (Exception e) {
            SilverLogger.getLogger(this).error(e.getMessage(), e);
        }
    }
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!//  ww  w  .  ja v  a  2s .  c  o  m
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.itracker.services.implementations.NotificationServiceImpl.java

private void handleSelfRegistrationNotification(String login, InternetAddress toAddress, String locale,
        String url) {//from  www  .  ja v a  2  s. c o  m
    if (logger.isDebugEnabled()) {
        logger.debug("handleSelfRegistrationNotification: called with login: " + login + ", toAddress"
                + toAddress + ", url: " + url);
    }
    try {

        if (toAddress != null && !"".equals(toAddress.getAddress())) {
            String subject = ITrackerResources.getString("itracker.email.selfreg.subject", locale);
            String msgText = ITrackerResources.getString("itracker.email.selfreg.body", locale,
                    new Object[] { login, url + "/login.do" });
            emailService.sendEmail(toAddress, subject, msgText);
        } else {
            throw new IllegalArgumentException("To-address must be set for self registration notification.");
        }
    } catch (RuntimeException e) {
        logger.error("failed to handle self registration notification for " + toAddress, e);
        throw e;
    }
}

From source file:org.obm.push.mail.MailBackendImpl.java

private Address validateFrom(InternetAddress address) throws ProcessingEmailException {
    String from = address.getAddress();
    if (from == null || !from.contains("@")) {
        throw new ProcessingEmailException("" + from + "is not a valid email");
    }/*w w  w  .  j a v a  2 s.  c o  m*/
    return new Address(from);
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//from   w  w  w .  j  a v a  2  s.co  m
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

            email.send();
        }
    } catch (Exception e) {
    } finally {
    }
}