Search in sources :

Example 6 with Transport

use of javax.mail.Transport in project symmetric-ds by JumpMind.

the class MailService method testTransport.

public String testTransport(TypedProperties prop) {
    String error = null;
    Transport transport = null;
    try {
        Session session = Session.getInstance(getJavaMailProperties(prop));
        transport = session.getTransport(prop.get(ParameterConstants.SMTP_TRANSPORT, "smtp"));
        if (prop.is(ParameterConstants.SMTP_USE_AUTH, false)) {
            transport.connect(prop.get(ParameterConstants.SMTP_USER), prop.get(ParameterConstants.SMTP_PASSWORD));
        } else {
            transport.connect();
        }
    } catch (NoSuchProviderException e) {
        error = getNestedErrorMessage(e);
    } catch (MessagingException e) {
        error = getNestedErrorMessage(e);
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException e) {
        }
    }
    return error;
}
Also used : MessagingException(javax.mail.MessagingException) Transport(javax.mail.Transport) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session)

Example 7 with Transport

use of javax.mail.Transport in project symmetric-ds by JumpMind.

the class MailService method sendEmail.

protected String sendEmail(String subject, String text, String recipients, Properties prop, String transportType, boolean useAuth, String user, String password) {
    Session session = Session.getInstance(prop);
    ByteArrayOutputStream ba = null;
    if (log.isDebugEnabled()) {
        session.setDebug(true);
        ba = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(ba);
        session.setDebugOut(ps);
    }
    Transport transport;
    try {
        transport = session.getTransport(transportType);
    } catch (NoSuchProviderException e) {
        log.error("Failure while obtaining transport", e);
        return getNestedErrorMessage(e);
    }
    try {
        if (useAuth) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }
    } catch (MessagingException e) {
        log.error("Failure while connecting to transport", e);
        return getNestedErrorMessage(e);
    }
    try {
        MimeMessage message = new MimeMessage(session);
        message.setSentDate(new Date());
        message.setRecipients(RecipientType.BCC, recipients);
        message.setSubject(subject);
        message.setText(text);
        try {
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            log.error("Failure while sending notification", e);
            return getNestedErrorMessage(e);
        }
    } catch (MessagingException e) {
        log.error("Failure while preparing notification", e);
        return e.getMessage();
    } finally {
        try {
            transport.close();
        } catch (MessagingException e) {
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(ba.toString());
    }
    return null;
}
Also used : PrintStream(java.io.PrintStream) MessagingException(javax.mail.MessagingException) MimeMessage(javax.mail.internet.MimeMessage) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Transport(javax.mail.Transport) NoSuchProviderException(javax.mail.NoSuchProviderException) Date(java.util.Date) Session(javax.mail.Session)

Example 8 with Transport

use of javax.mail.Transport in project libresonic by Libresonic.

the class RecoverController method emailPassword.

/*
    * e-mail user new password via configured Smtp server
    */
private boolean emailPassword(String password, String username, String email) {
    /* Default to protocol smtp when SmtpEncryption is set to "None" */
    String prot = "smtp";
    if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) {
        LOG.warn("Can not send email; no Smtp server configured.");
        return false;
    }
    Properties props = new Properties();
    if (settingsService.getSmtpEncryption().equals("SSL/TLS")) {
        prot = "smtps";
        props.put("mail." + prot + ".ssl.enable", "true");
    } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) {
        prot = "smtp";
        props.put("mail." + prot + ".starttls.enable", "true");
    }
    props.put("mail." + prot + ".host", settingsService.getSmtpServer());
    props.put("mail." + prot + ".port", settingsService.getSmtpPort());
    /* use authentication when SmtpUser is configured */
    if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) {
        props.put("mail." + prot + ".auth", "true");
    }
    Session session = Session.getInstance(props, null);
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settingsService.getSmtpFrom()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Libresonic Password");
        message.setText("Hi there!\n\n" + "You have requested to reset your Libresonic password.  Please find your new login details below.\n\n" + "Username: " + username + "\n" + "Password: " + password + "\n\n" + "--\n" + "Your Libresonic server\n" + "libresonic.org");
        message.setSentDate(new Date());
        Transport trans = session.getTransport(prot);
        try {
            if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) {
                trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword());
            } else {
                trans.connect();
            }
            trans.sendMessage(message, message.getAllRecipients());
        } finally {
            trans.close();
        }
        return true;
    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Transport(javax.mail.Transport) Date(java.util.Date) Session(javax.mail.Session)

Example 9 with Transport

use of javax.mail.Transport in project opennms by OpenNMS.

the class JavaSendMailer method send.

/**
     * Send.
     *
     * @param message the message
     * @throws JavaMailerException the java mailer exception
     */
public void send(MimeMessage message) throws JavaMailerException {
    Transport t = null;
    if (m_config.getSendmailProtocol() == null || m_config.getSendmailHost() == null) {
        throw new JavaMailerException("sendmail-protocol or sendmail-host are not configured!");
    }
    try {
        SendmailProtocol protoConfig = m_config.getSendmailProtocol();
        t = m_session.getTransport(protoConfig.getTransport());
        LOG.debug("for transport name '{}' got: {}@{}", protoConfig.getTransport(), t.getClass().getName(), Integer.toHexString(t.hashCode()));
        LoggingTransportListener listener = new LoggingTransportListener();
        t.addTransportListener(listener);
        if ("mta".equals(t.getURLName().getProtocol())) {
            // JMTA throws an AuthenticationFailedException if we call connect()
            LOG.debug("transport is 'mta', not trying to connect()");
        } else {
            final SendmailHost sendmailHost = m_config.getSendmailHost();
            if (m_config.isUseAuthentication() && m_config.getUserAuth() != null) {
                LOG.debug("authenticating to {}", sendmailHost.getHost());
                final UserAuth userAuth = m_config.getUserAuth();
                t.connect(sendmailHost.getHost(), sendmailHost.getPort(), userAuth.getUserName(), userAuth.getPassword());
            } else {
                LOG.debug("not authenticating to {}", sendmailHost.getHost());
                t.connect(sendmailHost.getHost(), sendmailHost.getPort(), null, null);
            }
        }
        t.sendMessage(message, message.getAllRecipients());
        listener.assertAllMessagesDelivered();
    } catch (NoSuchProviderException e) {
        LOG.error("Couldn't get a transport: {}", e, e);
        throw new JavaMailerException("Couldn't get a transport: " + e, e);
    } catch (MessagingException e) {
        LOG.error("Java Mailer messaging exception: {}", e, e);
        throw new JavaMailerException("Java Mailer messaging exception: " + e, e);
    } finally {
        try {
            if (t != null && t.isConnected()) {
                t.close();
            }
        } catch (MessagingException e) {
            throw new JavaMailerException("Java Mailer messaging exception on transport close: " + e, e);
        }
    }
}
Also used : SendmailProtocol(org.opennms.netmgt.config.javamail.SendmailProtocol) MessagingException(javax.mail.MessagingException) Transport(javax.mail.Transport) UserAuth(org.opennms.netmgt.config.javamail.UserAuth) NoSuchProviderException(javax.mail.NoSuchProviderException) SendmailHost(org.opennms.netmgt.config.javamail.SendmailHost)

Example 10 with Transport

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

the class SmtpTransportTest method dataError.

@Test(timeout = 3000)
public void dataError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine().sendLine("250 OK").recvLine().sendLine("250 OK").recvLine().sendLine("250 OK").recvLine().sendLine("451 error").recvLine().build().start(PORT);
    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(1, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(0, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }
    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}
Also used : SendFailedException(javax.mail.SendFailedException) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Transport(javax.mail.Transport) JMSession(com.zimbra.cs.util.JMSession) Session(javax.mail.Session) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) Test(org.junit.Test)

Aggregations

Transport (javax.mail.Transport)41 Session (javax.mail.Session)28 MimeMessage (javax.mail.internet.MimeMessage)24 JMSession (com.zimbra.cs.util.JMSession)18 MessagingException (javax.mail.MessagingException)18 Test (org.junit.Test)16 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)14 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)14 InternetAddress (javax.mail.internet.InternetAddress)11 Properties (java.util.Properties)9 Date (java.util.Date)7 Message (javax.mail.Message)6 NoSuchProviderException (javax.mail.NoSuchProviderException)6 SendFailedException (javax.mail.SendFailedException)6 IOException (java.io.IOException)5 SMTPMessage (com.sun.mail.smtp.SMTPMessage)2 SMTPTransport (com.sun.mail.smtp.SMTPTransport)2 Address (javax.mail.Address)2 Multipart (javax.mail.Multipart)2 AddressException (javax.mail.internet.AddressException)2