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() throws MessagingException 

Source Link

Document

A generic connect method that takes no parameters.

Usage

From source file:org.xmlactions.email.EMailSend.java

public static void sendEMail(String fromAddress, String toAddress, String host, String userName,
        String password, String subject, String msg) throws AddressException, MessagingException {

    log.debug(String.format(//  w  w  w .j  a  v a  2 s  .c o  m
            "sendEMail(from:%s, to:%s, host:%s, userName:%s, password:%s)\nsubject:{" + subject
                    + "\n}\nmessage:{" + msg + "\n}",
            fromAddress, toAddress, host, userName, toPassword(password), subject, msg));
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session;
    if (!StringUtils.isEmpty(password)) {
        props.put("mail.smtp.auth", "true");
        //EMailAuthenticator auth = new EMailAuthenticator(userName + "+" + host, password);
        EMailAuthenticator auth = new EMailAuthenticator(userName, password);
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }

    // Define message
    MimeMessage message = new MimeMessage(session);
    // message.setFrom(new InternetAddress("email_addresses@riostl.com"));
    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(toAddress));
    message.setSubject(subject);
    message.setText(msg);

    // Send message
    if (StringUtils.isEmpty(password)) {
        Transport.send(message);
    } else {
        Provider provider = session.getProvider("smtp");

        Transport transport = session.getTransport(provider);
        // Send message
        transport.connect();
        transport.sendMessage(message, new Address[] { new InternetAddress(toAddress) });
        transport.close();
    }

}

From source file:org.openmrs.module.sync.SyncMailUtil.java

public static String validateSettings(Map<String, String> settings) {
    MessageSourceService mss = Context.getMessageSourceService();
    try {//from  www.j a  v  a2  s.co m
        Session session = createSession(settings);
        Transport transport = session.getTransport();
        transport.connect();
        transport.close();
        return mss.getMessage("sync.emailConfig.connectionSuccessful");
    } catch (Exception e) {
        return mss.getMessage("sync.emailConfig.connectionFailed") + ": " + e.getMessage();
    }
}

From source file:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;
    try {/*from   w ww. jav  a2 s.  c  om*/
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;
    try {//from w  w  w .  jav a 2s .  c  om
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:portal.api.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody, String subj) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    if ((PortalRepository.getPropertyByName("mailhost").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", PortalRepository.getPropertyByName("mailhost").getValue());
    if ((PortalRepository.getPropertyByName("mailuser").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", PortalRepository.getPropertyByName("mailuser").getValue());
    if ((PortalRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", PortalRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = PortalRepository.getPropertyByName("adminEmail").getValue();
    final String username = PortalRepository.getPropertyByName("mailuser").getValue();
    final String password = PortalRepository.getPropertyByName("mailpassword").getValue();

    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from ww w  . j a v a2  s  .  co  m
    });

    Transport transport;
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(adminemail, adminemail));

        transport.connect();

        Address[] recips = (Address[]) ArrayUtils.addAll(msg.getRecipients(Message.RecipientType.TO),
                msg.getRecipients(Message.RecipientType.CC));

        transport.sendMessage(msg, recips);

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message//from  w  ww.j  ava 2 s  .c  om
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:net.jetrix.mail.MailSessionManager.java

/**
 * Check if the mail session is working properly.
 *///from   w  w w . ja  v a 2  s.c  om
public boolean checkSession() {
    boolean check = false;

    if (session != null) {
        try {
            Transport transport = session.getTransport();
            transport.connect();
            transport.close();

            check = true;
        } catch (MessagingException e) {
            log.warning("Unable to validate the mail session (" + e.getMessage() + ")");
        }
    }

    return check;
}

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {//from  ww w. j  a  v  a 2  s .  c o  m
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:at.molindo.notify.channel.mail.SimpleMailClient.java

private Transport connectTransport() throws MailException {
    try {/* w  w w  .  j  ava2  s. c  om*/
        Transport t = _smtpSession.getTransport("smtp");
        if (isConnect() && !t.isConnected()) {
            t.connect();
        }
        return t;
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("no SMTP provider?", e);
    } catch (MessagingException e) {
        throw new MailException("can't connect to SMTP server", e, true);
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param mimeMessage/*w  w  w . j av  a 2  s  .c om*/
 * @throws MessagingException
 */
private void _send(MimeMessage mimeMessage) throws MessagingException {

    Transport transport = null;

    try {

        transport = session.getTransport();
        transport.connect();

        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    } finally {
        if (transport != null && transport.isConnected()) {
            transport.close();
        }
    }
}