Example usage for javax.mail Authenticator Authenticator

List of usage examples for javax.mail Authenticator Authenticator

Introduction

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

Prototype

Authenticator

Source Link

Usage

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override//from   w  w w . jav  a2  s.c  o m
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

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

/**
 * Initialize the Mail sender and be ready to send messages
 * @param cfgCtx the axis2 configuration context
 * @param transportOut the transport-out description
 * @throws org.apache.axis2.AxisFault on error
 *///from w  w w.  j  av a  2 s . co m
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    setTransportName(MailConstants.TRANSPORT_NAME);
    super.init(cfgCtx, transportOut);

    // initialize SMTP session
    Properties props = new Properties();
    List<Parameter> params = transportOut.getParameters();
    for (Parameter p : params) {
        props.put(p.getName(), p.getValue());
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_FROM)) {
        try {
            smtpFromAddress = new InternetAddress((String) props.get(MailConstants.MAIL_SMTP_FROM));
        } catch (AddressException e) {
            handleException("Invalid default 'From' address : " + props.get(MailConstants.MAIL_SMTP_FROM), e);
        }
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_BCC)) {
        try {
            smtpBccAddresses = InternetAddress.parse((String) props.get(MailConstants.MAIL_SMTP_BCC));
        } catch (AddressException e) {
            handleException("Invalid default 'Bcc' address : " + props.get(MailConstants.MAIL_SMTP_BCC), e);
        }
    }

    if (props.containsKey(MailConstants.TRANSPORT_MAIL_FORMAT)) {
        defaultMailFormat = (String) props.get(MailConstants.TRANSPORT_MAIL_FORMAT);
    }

    smtpUsername = (String) props.get(MailConstants.MAIL_SMTP_USERNAME);
    smtpPassword = (String) props.get(MailConstants.MAIL_SMTP_PASSWORD);

    if (smtpUsername != null && smtpPassword != null) {
        session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        session = Session.getInstance(props, null);
    }

    // add handlers for main MIME types
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("application/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("application/soap+xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);

    session.setDebug(log.isTraceEnabled());
}

From source file:org.codice.ddf.platform.email.impl.SmtpClientImpl.java

Authenticator createAuthenticator() {
    return new Authenticator() {
        @Override/*  www  .  jav  a2s  .  c o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
}

From source file:io.mapzone.arena.EMailHelpDashlet.java

protected void initMailSession() {
    Properties props = new Properties();
    props.put("mail.smtp.host", System.getProperty("mail.smtp.host", smtpHost.get()));
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.auth", "true");
    // TODO uncomment if the mail server contains a correct SSL certificate
    // props.put( "mail.smtp.starttls.enable", "true" ); // enable STARTTLS

    // create Authenticator object to pass in Session.getInstance argument
    Authenticator auth = new Authenticator() {
        @Override// w ww  .j  av  a  2  s .  c  o m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUser.get(), smtpPassword.get());
        }
    };
    assert session == null;
    session = Session.getInstance(props, auth);
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

public Authenticator newAuthenticator() {
    return new Authenticator() {
        @Override//w  w  w .  j a  v a 2s  .  c  o m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
}

From source file:org.tomitribe.tribestream.registryng.service.monitoring.MailAlerter.java

@PostConstruct
private void init() {
    active = active && to != null;
    if (!active) {
        return;//from  w  w w  .  j  av a 2s. c  o  m
    }

    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        hostname = "unknown";
    }

    final Properties properties = new Properties();
    properties.setProperty("mail.transport.protocol", transport);
    properties.setProperty("mail." + transport + ".host", host);
    properties.setProperty("mail." + transport + ".port", Integer.toString(port));
    if (tls) {
        properties.setProperty("mail." + transport + ".starttls.enable", "true");
    }
    if (user != null) {
        properties.setProperty("mail." + transport + ".user", user);
    }
    if (password != null) {
        properties.setProperty("password", password);
    }
    if (auth || password != null) {
        properties.setProperty("mail." + transport + ".auth", "true");
    }
    if (timeout > 0) {
        properties.setProperty("mail." + transport + ".timeout", Integer.toString(timeout));
    }

    if (password != null) {
        final PasswordAuthentication pa = new PasswordAuthentication(user, password);
        session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return pa;
            }
        });
    } else {
        session = Session.getInstance(properties);
    }
}

From source file:com.app.mail.DefaultMailSender.java

private static Session _authenticateOutboundEmailAddress() {
    return Session.getInstance(PropertiesUtil.getConfigurationProperties(), new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(PropertiesValues.OUTBOUND_EMAIL_ADDRESS,
                    PropertiesValues.OUTBOUND_EMAIL_ADDRESS_PASSWORD);
        }//w  ww.j a va  2 s  . c  o  m

    });
}

From source file:com.datatorrent.lib.io.SmtpOutputOperator.java

private void reset() {
    if (!setupCalled) {
        return;//from ww  w  .j  a  va 2  s  .c  o  m
    }
    if (!StringUtils.isBlank(smtpPassword)) {
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        if (useSsl) {
            properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(smtpPort));
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        }

        auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUserName, smtpPassword);
            }

        };
    }

    properties.setProperty("mail.smtp.host", smtpHost);
    properties.setProperty("mail.smtp.port", String.valueOf(smtpPort));
    session = Session.getInstance(properties, auth);
    resetMessage();
}

From source file:com.mylab.mail.OpenCmsMailService.java

private Session getSession() {
    final CmsMailHost host = OpenCms.getSystemInfo().getMailSettings().getDefaultMailHost();
    Properties props = new Properties();
    props.put("mail.transport.protocol", host.getProtocol());
    props.put("mail.smtp.host", host.getHostname());
    props.put("mail.smtp.auth", host.isAuthenticating());

    Authenticator authenticator = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(host.getUsername(), host.getPassword());
        }/*from w  w  w  . ja va2s.  co m*/
    };

    return Session.getInstance(props, authenticator);
}

From source file:de.micromata.genome.util.runtime.config.MailSessionLocalSettingsConfigModel.java

public Session createMailSession(Properties addProperties) {
    Properties msprops = new Properties();

    msprops.put("mail.debug", Boolean.toString(smptDebug));
    msprops.put("mail.smtp.host", this.emailHost);
    msprops.put("mail.smtp.port", this.emailPort);
    //    msprops.put("mail.smtp.ssl.enable", "true");
    //msprops.put("mail.smtp.starttls.enable", "true");
    Encryption encr = Encryption.fromString(encryption);
    if (encr == Encryption.StartTLS) {
        msprops.put("mail.smtp.starttls.enable", "true");
    } else if (encr == Encryption.SSL) {
        msprops.put("mail.smtp.ssl.enable", "true");
        //      msprops.put("mail.smtp.socketFactory.port", emailPort);
        //      msprops.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }//  ww w  . ja  va 2 s.c  o m
    javax.mail.Session mailSession;
    msprops.put("mail.smtp.auth", Boolean.toString(isEmailAuthEnabled()));

    if (addProperties != null) {
        msprops.putAll(addProperties);
    }

    if (isEmailAuthEnabled() == true) {
        mailSession = Session.getInstance(msprops, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailAuthUser, emailAuthPass);
            }
        });
    } else {
        mailSession = Session.getInstance(msprops);
    }
    return mailSession;
}