Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

In this page you can find the example usage for javax.mail MessagingException MessagingException.

Prototype

public MessagingException(String s) 

Source Link

Document

Constructs a MessagingException with the specified detail message.

Usage

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

private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException {
    /*//from www  .  j  a  v a  2 s . c o  m
     * Find the existing PDF. The expect that the message is a multipart/mixed. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        throw new MessagingException("Content-type should have been multipart/mixed.");
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pdfPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart fallbackPart = null;

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pdfPart = part;

            break;
        }

        /*
         * Fallback scanning for application/pdf in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/pdf")) {
            fallbackPart = part;
        }
    }

    if (pdfPart == null) {
        if (fallbackPart != null) {
            getLogger().info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pdfPart = fallbackPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pdfPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf, "application/pdf")));
}

From source file:i2p.bote.I2PBote.java

public void sendEmail(Email email) throws MessagingException, PasswordException, IOException,
        GeneralSecurityException, DataFormatException {
    email.checkAddresses();/*from w  ww  .  jav a  2  s .  com*/

    // sign email unless sender is anonymous
    if (!email.isAnonymous()) {
        String sender = email.getOneFromAddress();
        EmailIdentity senderIdentity = identities.extractIdentity(sender);
        if (senderIdentity == null)
            throw new MessagingException(_t("No identity matches the sender/from field: " + sender));
        email.sign(senderIdentity, identities);
    }

    email.setSignatureFlag(); // set the signature flag so the signature isn't reverified every time the email is loaded
    outbox.add(email);
    if (outboxProcessor != null)
        outboxProcessor.checkForEmail();
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {/*from w  w w.jav  a2s  . c o m*/
            protocol = "smtps";
            // required to get rid of a SSL exception :
            //  nested exception is:
            //  javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (!Const.isEmpty(port))
        data.props.put("mail." + protocol + ".port", port);
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        data.props.put("mail.debug", "true");

    if (meta.isUsingAuthentication())
        data.props.put("mail." + protocol + ".auth", "true");

    Session session = Session.getInstance(data.props);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low"))
            priority_int = "3";
        if (meta.getPriority().equals("normal"))
            priority_int = "2";

        msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        //seems to be needed for MS Outlook.
        //where it returns a string of high /normal /low.
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName))
            email_address = senderName + '<' + email_address + '>';
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to 
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++)
            address[i] = new InternetAddress(reply_Address_List[i]);

        // To add the real reply-to 
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String destinations[] = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++)
        address[i] = new InternetAddress(destinations[i]);

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String destinationsCc[] = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++)
            addressCc[i] = new InternetAddress(destinationsCc[i]);

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String destinationsBCc[] = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++)
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null)
        msg.setSubject(mailsubject);

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null)
        messageText.append(comment).append(Const.CR).append(Const.CR);

    if (meta.getIncludeDate())
        messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson)
                .append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding()))
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        else
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
    } else
        part1.setText(messageText.toString());

    data.parts.addBodyPart(part1);

    // attached files
    if (meta.isDynamicFilename())
        setAttachedFilesList(r, log);
    else
        setAttachedFilesList(null, log);

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (!Const.isEmpty(port)) {
                transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")),
                        Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null)
            transport.close();
    }

}

From source file:com.openkm.util.impexp.RepositoryImporter.java

/**
 * Import mail.//from  www  . j  a v  a  2  s  .  co m
 */
private static ImpExpStats importMail(String token, String fldPath, String fileName, File fDoc,
        boolean metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                if (fileName.endsWith(".eml")) {
                    Session mailSession = Session.getDefaultInstance(props, null);
                    MimeMessage msg = new MimeMessage(mailSession, fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else if (fileName.endsWith(".msg")) {
                    Message msg = new MsgParser().parseMsg(fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else {
                    throw new MessagingException("Unknown mail format");
                }

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            if (fileName.endsWith(".eml")) {
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else if (fileName.endsWith(".msg")) {
                Message msg = new MsgParser().parseMsg(fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else {
                throw new MessagingException("Unknown mail format");
            }

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Messaging"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } catch (Exception e) {
        log.warn("Exception: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "General"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "Exception ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

public static void attach(MimeMultipart multipart, Vector attachments, String charset)
        throws MessagingException {
    for (int xindex = 0; xindex < attachments.size(); xindex++) {
        Object xobject = attachments.elementAt(xindex);

        // attach based on type of object
        if (xobject instanceof Part) {
            attach(multipart, (Part) xobject, charset);
        } else if (xobject instanceof File) {
            attach(multipart, (File) xobject, charset);
        } else if (xobject instanceof String) {
            attach(multipart, (String) xobject, charset, Part.ATTACHMENT, false);
        } else if (xobject instanceof vCard) {
            attach(multipart, (vCard) xobject, charset);
        } else {// ww w .  j  av  a2s. c  o m
            throw new MessagingException("Cannot attach objects of type " + xobject.getClass().getName());
        }
    }
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

public void _send(lucee.runtime.config.ConfigWeb config) throws MailException {

    long start = System.nanoTime();
    long _timeout = getTimeout(config, timeout);
    try {//from   w  w w  .  j a v  a2  s.  c o  m

        Proxy.start(proxyData);
        Log log = ((ConfigImpl) config).getLog("mail");
        // Server
        Server[] servers = config.getMailServers();
        if (host != null) {
            int prt;
            String usr, pwd;
            ServerImpl[] nServers = new ServerImpl[host.length];
            for (int i = 0; i < host.length; i++) {
                usr = null;
                pwd = null;
                prt = ServerImpl.DEFAULT_PORT;

                if (port > 0)
                    prt = port;
                if (!StringUtil.isEmpty(username)) {
                    usr = username;
                    pwd = password;
                }
                nServers[i] = toServerImpl(host[i], prt, usr, pwd, lifeTimespan, idleTimespan);
                if (ssl == SSL_YES)
                    nServers[i].setSSL(true);
                if (tls == TLS_YES)
                    nServers[i].setTLS(true);

            }
            servers = nServers;
        }
        if (servers.length == 0) {
            //return;
            throw new MailException("no SMTP Server defined");
        }

        boolean _ssl, _tls;
        for (int i = 0; i < servers.length; i++) {

            Server server = servers[i];
            String _username = null, _password = "";
            //int _port;

            // username/password

            if (server.hasAuthentication()) {
                _username = server.getUsername();
                _password = server.getPassword();
            }

            // tls
            if (tls != TLS_NONE)
                _tls = tls == TLS_YES;
            else
                _tls = ((ServerImpl) server).isTLS();

            // ssl
            if (ssl != SSL_NONE)
                _ssl = ssl == SSL_YES;
            else
                _ssl = ((ServerImpl) server).isSSL();

            MimeMessageAndSession msgSess;
            boolean recyleConnection = ((ServerImpl) server).reuseConnections();
            {//synchronized(LOCK) { no longer necessary we have a proxy lock now
                try {

                    msgSess = createMimeMessage(config, server.getHostName(), server.getPort(), _username,
                            _password, ((ServerImpl) server).getLifeTimeSpan(),
                            ((ServerImpl) server).getIdleTimeSpan(), _tls, _ssl, !recyleConnection);

                } catch (MessagingException e) {
                    // listener
                    listener(config, server, log, e, System.nanoTime() - start);
                    MailException me = new MailException(e.getMessage());
                    me.setStackTrace(e.getStackTrace());
                    throw me;
                }

                try {
                    SerializableObject lock = new SerializableObject();
                    SMTPSender sender = new SMTPSender(lock, msgSess, server.getHostName(), server.getPort(),
                            _username, _password, recyleConnection);
                    sender.start();
                    SystemUtil.wait(lock, _timeout);

                    if (!sender.isSent()) {
                        Throwable t = sender.getThrowable();
                        if (t != null)
                            throw Caster.toPageException(t);

                        // stop when still running
                        try {
                            if (sender.isAlive())
                                sender.stop();
                        } catch (Throwable t2) {
                        }

                        // after thread is stopped check sent flag again
                        if (!sender.isSent()) {
                            throw new MessagingException("timeout occurred after " + (_timeout / 1000)
                                    + " seconds while sending mail message");
                        }
                    }
                    clean(config, attachmentz);

                    listener(config, server, log, null, System.nanoTime() - start);
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                    if (i + 1 == servers.length) {

                        listener(config, server, log, e, System.nanoTime() - start);
                        MailException me = new MailException(
                                server.getHostName() + " " + ExceptionUtil.getStacktrace(e, true) + ":" + i);
                        me.setStackTrace(e.getStackTrace());

                        throw me;
                    }
                }
            }
        }
    } finally {
        Proxy.end();
    }
}

From source file:de.xirp.mail.MailManager.java

/**
 * Prints the corresponding {@link de.xirp.mail.Mail}
 * of the given {@link de.xirp.mail.MailDescriptor}.
 * /* w  ww  .  j a  v  a2s.  c  om*/
 * @param md
 *            The mail descriptor.
 * @throws MessagingException
 *             if something went wrong while printing.
 * @see de.xirp.mail.MailDescriptor
 * @see de.xirp.mail.Mail
 */
public static void printMail(MailDescriptor md) throws MessagingException {
    try {
        Mail mail = getMail(md);

        List<File> docs = new ArrayList<File>();

        long millis = System.currentTimeMillis();

        File text = new File(Constants.TMP_DIR, millis + "_printtmp_mailtext.txt"); //$NON-NLS-1$
        text.createNewFile();
        docs.add(text);
        DeleteManager.deleteOnShutdown(text);
        FileUtils.writeStringToFile(text, md.getSubject(), "Unicode"); //$NON-NLS-1$

        for (Attachment a : mail.getAttachments()) {
            if (a.isPrintable()) {
                File attachment = new File(Constants.TMP_DIR, millis + "_printtmp_" + a.getFileName()); //$NON-NLS-1$
                attachment.createNewFile();
                docs.add(attachment);
                DeleteManager.deleteOnShutdown(attachment);
                FileUtils.writeByteArrayToFile(attachment, a.getAttachmentFileContent());
            }
        }
        PrintManager.print(docs);
    } catch (FileNotFoundException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    } catch (SerializationException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/* w  ww.j  av a  2s  . c  o  m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this
                                // file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:com.sonicle.webtop.mail.MailAccount.java

public String renameFolder(String orig, String newname) throws MessagingException {
    FolderCache fc = getFolderCache(orig);
    FolderCache fcparent = fc.getParent();
    Folder oldfolder = fc.getFolder();// w  w w. j a  va2 s.c o m
    destroyFolderCache(fc);
    Folder newfolder = fcparent.getFolder().getFolder(newname);
    boolean done = oldfolder.renameTo(newfolder);
    if (!done) {
        throw new MessagingException("Rename failed");
    }

    //trick for Dovecot on NethServer: under shared folders, create and destroy a fake folder
    //or rename will not work correctly
    if (isUnderSharedFolder(newfolder.getFullName())) {
        Map<String, String> map = ((IMAPStore) store).id(null);
        if (map != null && map.containsKey("name") && map.get("name").equalsIgnoreCase("dovecot")) {
            String trickName = "_________" + System.currentTimeMillis();
            Folder trickFolder = fcparent.getFolder().getFolder(trickName);
            try {
                trickFolder.create(Folder.READ_ONLY);
                trickFolder.delete(true);
            } catch (MessagingException exc) {

            }
        }
    }

    addFoldersCache(fcparent, newfolder);
    return newfolder.getFullName();
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Decode contents of TEXT/PLAIN message parts into UTF encoded strings.
 * Why can't JAVA Mail provide this method?? Who knows!?!?!?
 *
 * @param buffer DOCUMENT ME!//  w w  w  .j  av  a2  s. c o m
 * @param part DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer decodeTextPlain(StringBuffer buffer, Part part, String breakLine, String charset)
        throws MessagingException {
    // pick off the individual lines of text
    // and append to the buffer
    try {
        StringBuffer buff = new StringBuffer();

        BufferedReader xreader = MessageUtilities.getTextReader(part.getInputStream(), charset);

        for (String xline; (xline = xreader.readLine()) != null;) {
            buff.append(xline);
            buff.append(breakLine);
        }

        xreader.close();

        //String aux = JavaScriptFilter.apply(buff.toString());
        buffer.append(buff.toString());

        return buffer;
    } catch (IOException xex) {
        throw new MessagingException(xex.toString());
    }
}