Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

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

Prototype

public static Session getInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:webreader.WebReader.java

private void sendEmail(String inputMessage) {
    //---User login information
    final String username = email;
    final String password = emailPassword;

    //---Sets server for gmail
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    //---Creates a new session
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);

        }//ww  w .  jav a 2  s  . c  o m

    });
    //---Try catch loop for sending an email
    //---Sends error email to the sender if catch is engaged.
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject("Your grades have been updated");
        message.setText(inputMessage);
        Transport.send(message);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        emailSent = "E-mail was sent: " + dateFormat.format(date);
        System.out.println(emailSent);
    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //---Used code from https://www.youtube.com/watch?v=sHC8YgW21ho
    //---for the above method
}

From source file:org.springframework.integration.mail.AbstractMailReceiver.java

private void openSession() throws MessagingException {
    if (this.session == null) {
        if (this.javaMailAuthenticator != null) {
            this.session = Session.getInstance(this.javaMailProperties, this.javaMailAuthenticator);
        } else {//from   ww w .  ja  va 2  s  . co m
            this.session = Session.getInstance(this.javaMailProperties);
        }
    }
    if (this.store == null) {
        if (this.url != null) {
            this.store = this.session.getStore(this.url);
        } else if (this.protocol != null) {
            this.store = this.session.getStore(this.protocol);
        } else {
            this.store = this.session.getStore();
        }
    }
    if (!this.store.isConnected()) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "connecting to store [" + MailTransportUtils.toPasswordProtectedString(this.url) + "]");
        }
        this.store.connect();
    }
}

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");
    }/*from   ww w . j ava2 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;
}

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

private void reset() {
    if (!setupCalled) {
        return;/*  w  w  w .j ava  2 s  . com*/
    }
    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 .  j  a va  2s .  c  om*/
    };

    return Session.getInstance(props, authenticator);
}

From source file:org.entermedia.email.PostMail.java

public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject,
        String inHtml, String inText, String from, List inAttachments, Map inProperties)
        throws MessagingException {
    // Set the host smtp address
    Properties props = new Properties();
    // create some properties and get the default Session
    props.put("mail.smtp.host", fieldSmtpServer);
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString());
    if (isSslEnabled()) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }//  w w  w  .  ja  v a  2 s .  c o m
    Session session = null;
    if (isEnableTls()) {
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword());
            }
        });
    } else if (fieldSmtpSecured) {
        SmtpAuthenticator auth = new SmtpAuthenticator();
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }
    // session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);
    MimeMultipart mp = null;
    // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message,
    // "text/html")));

    if (inAttachments != null && inAttachments.size() == 0) {
        inAttachments = null;
    }

    if (inText != null && inHtml != null || inAttachments != null) {
        // Create an "Alternative" Multipart message
        mp = new MimeMultipart("mixed");

        if (inText != null) {
            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(inText, "text/plain");
            mp.addBodyPart(messageBodyPart);
        }
        if (inHtml != null) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(inHtml, "text/html");
            mp.addBodyPart(messageBodyPart);
        }
        if (inAttachments != null) {
            for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) {
                String filename = (String) iterator.next();

                File file = new File(filename);

                if (file.exists() && !file.isDirectory()) {
                    // create the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));

                    mbp.setFileName(fds.getName());

                    mp.addBodyPart(mbp);
                }
            }
        }

        msg.setContent(mp);

    } else if (inHtml != null) {
        msg.setContent(inHtml, "text/html");
    } else {
        msg.setContent(inText, "text/plain");
    }
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    //msg.setRecipient(RecipientType.BCC, addressFrom);
    msg.setSentDate(new Date());
    if (recipients == null || recipients.isEmpty()) {
        throw new MessagingException("No recipients specified");
    }
    InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]);

    msg.setRecipients(Message.RecipientType.TO, addressTo);

    //add bcc
    if (blindrecipients != null && !blindrecipients.isEmpty()) {
        InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]);
        msg.setRecipients(Message.RecipientType.BCC, addressBcc);
    }

    // Optional : You can also set your custom headers in the Email if you
    // Want
    // msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);

    // Transport tr = session.getTransport("smtp");
    // tr.connect(serverandport[0], null, null);
    // msg.saveChanges(); // don't forget this
    // tr.sendMessage(msg, msg.getAllRecipients());
    // tr.close();
    // msg.setContent(msg, "text/plain");

    Transport.send(msg);
    log.info("sent email " + subject);
}

From source file:com.smartitengineering.emailq.binder.guice.EmailModule.java

private void configureJavaMailSession() {
    Properties properties = new Properties();
    properties.setProperty(JAVAMAIL_SMTP_HOST, smtpHost);
    properties.setProperty(JAVAMAIL_SMTP_PORT, String.valueOf(smtpPort));
    if (sslEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_CLASS,
                JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_CLASS_VAL);
        properties.setProperty(JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_PORT, String.valueOf(smtpPort));
    } else if (tlsEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_TLS, String.valueOf(tlsEnabled));
    }/*w w  w  .j a va 2s .  c  om*/
    if (authEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_USER, smtpUser);
        properties.setProperty(JAVAMAIL_SMTP_AUTH, String.valueOf(authEnabled));
        bind(Session.class).toInstance(Session.getInstance(properties, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUser, smtpPassword);
            }
        }));
    } else {
        bind(Session.class).toInstance(Session.getInstance(properties));
    }
}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/*ww w.  j  a  v a 2  s  .com*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.hs.mail.smtp.message.SmtpMessage.java

public MimeMessage getMimeMessage() throws MessagingException {
    Session session = Session.getInstance(System.getProperties(), null);
    InputStream is = null;//www.  j  a v a 2  s .  co  m
    try {
        is = new FileInputStream(getDataFile());
        return new MimeMessage(session, is);
    } catch (FileNotFoundException e) {
        throw new MessagingException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param user//from  ww  w . j ava  2s  .c  o  m
 * @param pwd
 * @return
 */
public static Session newSession(String user, String pwd) {
    return Session.getInstance(System.getProperties(),
            isEmpty(user) ? null : new DefaultAuthenticator(user, pwd));
}