Search in sources :

Example 1 with SendFailedException

use of javax.mail.SendFailedException in project Openfire by igniterealtime.

the class SendMail method sendMessage.

public boolean sendMessage(String message, String host, String port, String username, String password) {
    boolean ok = false;
    String uidString = "";
    try {
        // Set the email properties necessary to send email
        final Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.server", host);
        if (ModelUtil.hasLength(port)) {
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", port);
        }
        Session sess;
        if (ModelUtil.hasLength(password) && ModelUtil.hasLength(username)) {
            sess = Session.getInstance(props, new MailAuthentication(username, password));
        } else {
            sess = Session.getDefaultInstance(props, null);
        }
        Message msg = new MimeMessage(sess);
        StringTokenizer toST = new StringTokenizer(toField, ",");
        if (toST.countTokens() > 1) {
            InternetAddress[] address = new InternetAddress[toST.countTokens()];
            int addrIndex = 0;
            String addrString = "";
            while (toST.hasMoreTokens()) {
                addrString = toST.nextToken();
                address[addrIndex] = (new InternetAddress(addrString));
                addrIndex = addrIndex + 1;
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toField) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        InternetAddress from = new InternetAddress(myAddress);
        msg.setFrom(from);
        msg.setSubject(subjectField);
        UID msgUID = new UID();
        uidString = msgUID.toString();
        msg.setHeader("X-Mailer", uidString);
        msg.setSentDate(new Date());
        MimeMultipart mp = new MimeMultipart();
        // create body part for textarea
        MimeBodyPart mbp1 = new MimeBodyPart();
        if (getCustomerName() != null) {
            messageText = "From: " + getCustomerName() + "\n" + messageText;
        }
        if (isHTML) {
            mbp1.setContent(messageText, "text/html");
        } else {
            mbp1.setContent(messageText, "text/plain");
        }
        mp.addBodyPart(mbp1);
        try {
            if (!isHTML) {
                msg.setContent(messageText, "text/plain");
            } else {
                msg.setContent(messageText, "text/html");
            }
            Transport.send(msg);
            ok = true;
        } catch (SendFailedException sfe) {
            Log.warn("Could not connect to SMTP server.");
        }
    } catch (Exception eq) {
        Log.warn("Could not connect to SMTP server.");
    }
    return ok;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Date(java.util.Date) SendFailedException(javax.mail.SendFailedException) UID(java.rmi.server.UID) StringTokenizer(java.util.StringTokenizer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 2 with SendFailedException

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

the class EMail method send.

/**
	 *	Send Mail direct
	 *	@return OK or error message
	 */
public String send() {
    log.info("(" + m_Host + ") " + m_from + " -> " + m_to);
    m_sentMsg = null;
    //
    if (!isValid(true)) {
        m_sentMsg = "Invalid Data";
        return m_sentMsg;
    }
    //	FR [ 402 ]
    Session session = null;
    try {
        session = getSession();
    } catch (SecurityException se) {
        log.log(Level.WARNING, "Auth=" + m_auth + " - " + se.toString());
        m_sentMsg = se.toString();
        return se.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Auth=" + m_auth, e);
        m_sentMsg = e.toString();
        return e.toString();
    }
    try {
        m_msg = new SMTPMessage(session);
        //	Addresses
        m_msg.setFrom(m_from);
        InternetAddress[] rec = getTos();
        if (rec.length == 1)
            m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
        else
            m_msg.setRecipients(Message.RecipientType.TO, rec);
        rec = getCcs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.CC, rec);
        rec = getBccs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.BCC, rec);
        if (m_replyTo != null)
            m_msg.setReplyTo(new Address[] { m_replyTo });
        //
        m_msg.setSentDate(new java.util.Date());
        m_msg.setHeader("Comments", "AdempiereMail");
        //	SMTP specifics
        m_msg.setAllow8bitMIME(true);
        //	Send notification on Failure & Success - no way to set envid in Java yet
        //	Bounce only header
        m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
        //
        setContent();
        m_msg.saveChanges();
        log.fine("message =" + m_msg);
        //
        getTransport(session);
        Transport.send(m_msg);
        log.fine("Success - MessageID=" + m_msg.getMessageID());
    } catch (MessagingException me) {
        Exception ex = me;
        StringBuffer sb = new StringBuffer("(ME)");
        boolean printed = false;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (!printed) {
                    if (invalid != null && invalid.length > 0) {
                        sb.append(" - Invalid:");
                        for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]);
                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null && validUnsent.length > 0) {
                        sb.append(" - ValidUnsent:");
                        for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]);
                    }
                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null && validSent.length > 0) {
                        sb.append(" - ValidSent:");
                        for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]);
                    }
                    printed = true;
                }
                if (sfex.getNextException() == null)
                    sb.append(" ").append(sfex.getLocalizedMessage());
            } else if (ex instanceof AuthenticationFailedException) {
                sb.append(" - Invalid Username/Password - " + m_auth);
            } else //	other MessagingException 
            {
                String msg = ex.getLocalizedMessage();
                if (msg == null)
                    sb.append(": ").append(ex.toString());
                else {
                    if (msg.indexOf("Could not connect to SMTP host:") != -1) {
                        int index = msg.indexOf('\n');
                        if (index != -1)
                            msg = msg.substring(0, index);
                        String cc = "??";
                        if (m_ctx != null)
                            cc = m_ctx.getProperty("#AD_Client_ID");
                        msg += " - AD_Client_ID=" + cc;
                    }
                    String className = ex.getClass().getName();
                    if (className.indexOf("MessagingException") != -1)
                        sb.append(": ").append(msg);
                    else
                        sb.append(" ").append(className).append(": ").append(msg);
                }
            }
            //	Next Exception
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (//	error loop
        ex != null);
        //
        if (CLogMgt.isLevelFinest())
            log.log(Level.WARNING, sb.toString(), me);
        else
            log.log(Level.WARNING, sb.toString());
        m_sentMsg = sb.toString();
        return sb.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        m_sentMsg = e.getLocalizedMessage();
        return e.getLocalizedMessage();
    }
    //
    if (CLogMgt.isLevelFinest())
        dumpMessage();
    m_sentMsg = SENT_OK;
    return m_sentMsg;
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) SendFailedException(javax.mail.SendFailedException) IOException(java.io.IOException) Session(javax.mail.Session)

Example 3 with SendFailedException

use of javax.mail.SendFailedException in project Lucee by lucee.

the class SMTPSender method run.

@Override
public void run() {
    Transport transport = null;
    try {
        // SMTPConnectionPool.getTransport(session,host,port,user,pass);
        transport = mmas.session.transport;
        if (user == null)
            pass = null;
        // connect
        if (!transport.isConnected())
            transport.connect(host, port, user, pass);
        mmas.message.saveChanges();
        transport.sendMessage(mmas.message, mmas.message.getAllRecipients());
        isSent = true;
    } catch (SendFailedException sfe) {
        Address[] valid = sfe.getValidSentAddresses();
        // a soon the mail was send to one reciever we do no longer block it
        if (valid != null && valid.length > 0)
            isSent = true;
        this.throwable = sfe;
    } catch (Exception e) {
        this.throwable = e;
    } finally {
        try {
            if (recyleConnection)
                SMTPConnectionPool.releaseSessionAndTransport(mmas.session);
            else
                SMTPConnectionPool.disconnect(mmas.session.transport);
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }
        SystemUtil.notify(lock);
    }
}
Also used : SendFailedException(javax.mail.SendFailedException) Transport(javax.mail.Transport) SendFailedException(javax.mail.SendFailedException)

Example 4 with SendFailedException

use of javax.mail.SendFailedException in project pentaho-platform by pentaho.

the class EmailComponent method executeAction.

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();
    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;
    }
    if (ComponentBase.debug) {
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
    }
    if ((to == null) || (to.trim().length() == 0)) {
        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            true);
            // $NON-NLS-1$
            setFeedbackMimeType("text/html");
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
        return false;
    }
    if (getRuntimeContext().isPromptPending()) {
        return true;
    }
    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));
        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", decrypt(service.getEmailConfig().getPassword()));
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }
        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }
        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            // $NON-NLS-1$
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
        }
        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }
        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                // $NON-NLS-1$
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
            }
            if (messageHtml != null) {
                // $NON-NLS-1$
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                // $NON-NLS-1$
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(htmlBodyPart);
            }
            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                // $NON-NLS-1$
                textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(textBodyPart);
            }
            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    // $NON-NLS-1$
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    // $NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
                }
                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    // $NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }
            // add the Multipart to the message
            msg.setContent(multipart);
        }
        // $NON-NLS-1$
        msg.setHeader("X-Mailer", EmailComponent.MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        if (ComponentBase.debug) {
            // $NON-NLS-1$
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
        }
        return true;
    // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    /*
       * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
       * MessagingException) { sfe = (MessagingException) ne;
       * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
       * //$NON-NLS-1$ }
       */
    } catch (AuthenticationFailedException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
    } catch (Throwable e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    }
    return false;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) SendFailedException(javax.mail.SendFailedException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) EmailAttachment(org.pentaho.actionsequence.dom.actions.EmailAttachment) OutputStream(java.io.OutputStream) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) IPentahoStreamSource(org.pentaho.commons.connection.IPentahoStreamSource) Date(java.util.Date) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ActivationHelper(org.pentaho.commons.connection.ActivationHelper) EmailAction(org.pentaho.actionsequence.dom.actions.EmailAction) MimeBodyPart(javax.mail.internet.MimeBodyPart) IEmailService(org.pentaho.platform.api.email.IEmailService) Authenticator(javax.mail.Authenticator) Session(javax.mail.Session)

Example 5 with SendFailedException

use of javax.mail.SendFailedException in project gitblit by gitblit.

the class MailService method run.

@Override
public void run() {
    if (!queue.isEmpty()) {
        if (session != null) {
            // send message via mail server
            List<Message> failures = new ArrayList<Message>();
            Message message = null;
            while ((message = queue.poll()) != null) {
                try {
                    if (settings.getBoolean(Keys.mail.debug, false)) {
                        logger.info("send: '" + StringUtils.trimString(message.getSubject(), 60) + "' to:" + StringUtils.trimString(Arrays.toString(message.getAllRecipients()), 300));
                    }
                    Transport.send(message);
                } catch (SendFailedException sfe) {
                    if (settings.getBoolean(Keys.mail.debug, false)) {
                        logger.error("Failed to send message: {}", sfe.getMessage());
                        logger.info("   Invalid addresses: {}", Arrays.toString(sfe.getInvalidAddresses()));
                        logger.info("   Valid sent addresses: {}", Arrays.toString(sfe.getValidSentAddresses()));
                        logger.info("   Valid unset addresses: {}", Arrays.toString(sfe.getValidUnsentAddresses()));
                        logger.info("", sfe);
                    } else {
                        logger.error("Failed to send message: {}", sfe.getMessage(), sfe.getNextException());
                    }
                    failures.add(message);
                } catch (Throwable e) {
                    logger.error("Failed to send message", e);
                    failures.add(message);
                }
            }
            // push the failures back onto the queue for the next cycle
            queue.addAll(failures);
        }
    }
}
Also used : SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList)

Aggregations

SendFailedException (javax.mail.SendFailedException)23 MimeMessage (javax.mail.internet.MimeMessage)15 Session (javax.mail.Session)14 MessagingException (javax.mail.MessagingException)13 Transport (javax.mail.Transport)11 InternetAddress (javax.mail.internet.InternetAddress)11 IOException (java.io.IOException)9 MimeBodyPart (javax.mail.internet.MimeBodyPart)8 MimeMultipart (javax.mail.internet.MimeMultipart)8 Properties (java.util.Properties)7 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)6 JMSession (com.zimbra.cs.util.JMSession)5 Date (java.util.Date)5 DataHandler (javax.activation.DataHandler)5 Address (javax.mail.Address)5 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)5 Test (org.junit.Test)4 SMTPMessage (com.sun.mail.smtp.SMTPMessage)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3