Example usage for javax.mail Transport connect

List of usage examples for javax.mail Transport connect

Introduction

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

Prototype

public void connect(String host, String user, String password) throws MessagingException 

Source Link

Document

Connect to the specified address.

Usage

From source file:com.zimbra.cs.util.SmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();//from   ww  w  .ja v a  2  s . c o  m
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }

    String file = null;
    if (!cl.hasOption("f")) {
        usage("no file specified");
    } else {
        file = cl.getOptionValue("f");
    }
    try {
        ByteUtil.getContent(new File(file));
    } catch (IOException ioe) {
        usage(ioe.getMessage());
    }

    String host = null;
    if (!cl.hasOption("a")) {
        usage("no smtp server specified");
    } else {
        host = cl.getOptionValue("a");
    }

    String sender = null;
    if (!cl.hasOption("s")) {
        usage("no sender specified");
    } else {
        sender = cl.getOptionValue("s");
    }

    String recipient = null;
    if (!cl.hasOption("r")) {
        usage("no recipient specified");
    } else {
        recipient = cl.getOptionValue("r");
    }

    boolean trace = false;
    if (cl.hasOption("T")) {
        trace = true;
    }

    boolean tls = false;
    if (cl.hasOption("t")) {
        tls = true;
    }

    boolean auth = false;
    String user = null;
    String password = null;
    if (cl.hasOption("A")) {
        auth = true;
        if (!cl.hasOption("u")) {
            usage("auth enabled, no user specified");
        } else {
            user = cl.getOptionValue("u");
        }
        if (!cl.hasOption("p")) {
            usage("auth enabled, no password specified");
        } else {
            password = cl.getOptionValue("p");
        }
    }

    if (cl.hasOption("v")) {
        mLog.info("SMTP server: " + host);
        mLog.info("Sender: " + sender);
        mLog.info("Recipient: " + recipient);
        mLog.info("File: " + file);
        mLog.info("TLS: " + tls);
        mLog.info("Auth: " + auth);
        if (auth) {
            mLog.info("User: " + user);
            char[] dummyPassword = new char[password.length()];
            Arrays.fill(dummyPassword, '*');
            mLog.info("Password: " + new String(dummyPassword));
        }
    }

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);

    if (auth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    if (tls) {
        props.put("mail.smtp.starttls.enable", "true");
    } else {
        props.put("mail.smtp.starttls.enable", "false");
    }

    // Disable certificate checking so we can test against
    // self-signed certificates
    props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory());

    Session session = Session.getInstance(props, null);
    session.setDebug(trace);

    try {
        // create a message
        MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file));
        InternetAddress[] address = { new JavaMailInternetAddress(recipient) };
        msg.setFrom(new JavaMailInternetAddress(sender));

        // attach the file to the message
        Transport transport = session.getTransport("smtp");
        transport.connect(null, user, password);
        transport.sendMessage(msg, address);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:lucee.runtime.net.mail.SMTPVerifier.java

private static boolean _verify(String host, String username, String password, int port)
        throws MessagingException {
    boolean hasAuth = !StringUtil.isEmpty(username);

    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (hasAuth)//w w w. j  ava  2  s .  c  om
        props.put("mail.smtp.auth", "true");
    if (hasAuth)
        props.put("mail.smtp.user", username);
    if (hasAuth)
        props.put("mail.transport.connect-timeout", "30");
    if (port > 0)
        props.put("mail.smtp.port", String.valueOf(port));

    Authenticator auth = null;
    if (hasAuth)
        auth = new DefaultAuthenticator(username, password);
    Session session = Session.getInstance(props, auth);

    Transport transport = session.getTransport("smtp");
    if (hasAuth)
        transport.connect(host, username, password);
    else
        transport.connect();
    boolean rtn = transport.isConnected();
    transport.close();

    return rtn;
}

From source file:org.bml.util.mail.MailUtils.java

/**
 * Simple mail utility/*from   www.  ja v a  2  s . c om*/
 * @param sendToAdresses email addresses to send the mail to
 * @param emailSubjectLine the subject of the email.
 * @param emailBody The body of the mail
 * @param smtpHost the smtp host
 * @param sender the mail address that is the sender
 * @param smtpPassword the password for the sender
 * @param smtpPort the port to contact the smtp server on
 * @return boolean true on success and false on error
 */
public static boolean sendMail(final String[] sendToAdresses, final String emailSubjectLine,
        final String emailBody, final String smtpHost, String sender, String smtpPassword, final int smtpPort) {
    if ((sendToAdresses == null) || (sendToAdresses.length == 0)) {
        return false;
    }

    if ((emailSubjectLine == null) || (emailBody == null)) {
        return false;
    }

    try {
        Address[] addresses = new Address[sendToAdresses.length];
        for (int i = 0; i < sendToAdresses.length; i++) {
            addresses[i] = new InternetAddress(sendToAdresses[i]);
        }

        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtpHost);
        props.setProperty("mail.smtp.localhost", smtpHost);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", String.valueOf(smtpPort));
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, null);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setRecipients(Message.RecipientType.TO, addresses);
        message.setSubject(emailSubjectLine);
        message.setContent(emailBody, "text/plain");
        message.saveChanges();

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, sender, smtpPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (Throwable t) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error occured while sending mail.", t);
        }
        return false;
    }
    return true;
}

From source file:com.liferay.util.mail.MailEngine.java

private static void _sendMessage(Session session, Message msg) throws MessagingException {

    boolean smtpAuth = GetterUtil.getBoolean(session.getProperty("mail.smtp.auth"), false);
    String smtpHost = session.getProperty("mail.smtp.host");
    String user = session.getProperty("mail.smtp.user");
    String password = session.getProperty("mail.smtp.password");

    if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) {

        Transport tr = session.getTransport("smtp");
        tr.connect(smtpHost, user, password);
        tr.sendMessage(msg, msg.getAllRecipients());
        tr.close();/* w ww  .j a  va2s.  co m*/
    } else {
        Transport.send(msg);
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*from   w  w  w . jav  a 2  s  . c  o  m*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:ee.cyber.licensing.service.MailService.java

private static void sendMail(String email, String password, String host, Session getMailSession,
        MimeMessage mailMessage) throws MessagingException {
    Transport transport = getMailSession.getTransport("smtp");

    // if you have 2FA enabled then provide App Specific Password
    transport.connect(host, email, password);
    transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
    transport.close();//from   ww  w .ja  v  a2 s .c o m
    logger.info("6th ===> Email Sent Successfully With Image Attachment");
    logger.info("7th ===> generateAndSendEmail() ended");
}

From source file:isl.FIMS.utils.Utils.java

public static boolean sendEmail(String to, String subject, String context) {
    boolean isSend = false;

    try {/*from   w  w  w  . java  2  s  . c om*/

        String host = "smtp.gmail.com";
        String user = emailAdress;
        String password = emailPass;

        String port = "587";
        String from = "no-reply-" + systemName + "@gmail.com";
        Properties props = System.getProperties();

        props.put("mail.smtp.user", user);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        //  props.put("mail.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");
        //     props.put("mail.smtp.socketFactory.port", port);
        //    props.put("mail.smtp.socketFactory.class",
        //            "javax.net.ssl.SSLSocketFactory");
        //    props.put("mail.smtp.port", "465");

        Session session = Session.getInstance(props, null);
        //session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        // To get the array of addresses
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject(subject, "UTF-8");
        message.setContent(context, "text/html; charset=UTF-8");
        Transport transport = session.getTransport("smtp");
        try {
            transport.connect(host, user, password);
            transport.sendMessage(message, message.getAllRecipients());
        } finally {
            transport.close();
        }
        isSend = true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return isSend;

}

From source file:easyproject.service.Mail.java

public void sendMail() {
    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

    Session session = Session.getInstance(props, null);

    try {/*www .j  a  v a 2 s .  c o  m*/
        MimeMessage message = new MimeMessage(session);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message.setSubject(asunto);
        message.setSentDate(new Date());
        message.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:cl.preguntame.controller.PlataformaController.java

@ResponseBody
@RequestMapping(value = "/email", method = RequestMethod.POST)
public String correo(HttpServletRequest req) {

    try {/*from  ww  w.j  a  v  a  2 s  . co m*/
        String host = "smtp.gmail.com";

        Properties prop = System.getProperties();

        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", "hector.riquelme1169@gmail.com");
        prop.put("mail.smtp.password", "rriiqquueellmmee");
        prop.put("mail.smtp.port", 587);
        prop.put("mail.smtp.auth", "true");

        Session sesion = Session.getDefaultInstance(prop, null);
        MimeMessage mensaje = new MimeMessage(sesion);

        mensaje.setFrom(new InternetAddress());
        mensaje.setRecipient(Message.RecipientType.TO, new InternetAddress("hector.riquelme1169@gmail.com"));
        mensaje.setSubject("CONTACTO MIS CONCEPTOS");
        mensaje.setText(req.getParameter("mensaje_contacto"));

        Transport transport = sesion.getTransport("smtp");
        transport.connect(host, "hector.riquelme1169@gmail.com", "rriiqquueellmmee");
        transport.sendMessage(mensaje, mensaje.getAllRecipients());

        transport.close();

    } catch (Exception e) {

    }

    return req.getParameter("mensaje_contacto") + "  -  " + req.getParameter("email_contacto");
}

From source file:easyproject.utils.SendMail.java

@Override
public void run() {

    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

    Session session = Session.getInstance(props, null);

    try {//from  w ww .j a v a  2 s  .c  om
        MimeMessage message1 = new MimeMessage(session);

        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message1.setSubject(asunto);
        message1.setSentDate(new Date());
        message1.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message1.saveChanges();
        tr.sendMessage(message1, message1.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }

}