Example usage for javax.mail Session getDefaultInstance

List of usage examples for javax.mail Session getDefaultInstance

Introduction

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

Prototype

public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get the default Session object.

Usage

From source file:net.wastl.webmail.server.WebMailServer.java

protected void initProviders() {
    possible_providers = Session.getDefaultInstance(System.getProperties(), null).getProviders();
    log.info("Mail providers:");
    config_scheme.configRegisterChoiceKey("DEFAULT PROTOCOL", "Protocol to be used as default");
    int p_transport = 0;
    int p_store = 0;
    for (int i = 0; i < possible_providers.length; i++) {
        log.info(possible_providers[i].getProtocol() + " from " + possible_providers[i].getVendor());
        if (possible_providers[i].getType() == Provider.Type.STORE) {
            p_store++;//from   w w  w .ja  v  a  2s .c om
            config_scheme.configAddChoice("DEFAULT PROTOCOL", possible_providers[i].getProtocol(), "Use "
                    + possible_providers[i].getProtocol() + " from " + possible_providers[i].getVendor());
            config_scheme.configRegisterYesNoKey("ENABLE " + possible_providers[i].getProtocol().toUpperCase(),
                    "Enable " + possible_providers[i].getProtocol() + " from "
                            + possible_providers[i].getVendor());
        } else {
            p_transport++;
        }
    }
    store_providers = new Provider[p_store];
    transport_providers = new Provider[p_transport];
    p_store = 0;
    p_transport = 0;
    for (int i = 0; i < possible_providers.length; i++) {
        if (possible_providers[i].getType() == Provider.Type.STORE) {
            store_providers[p_store] = possible_providers[i];
            p_store++;
        } else {
            transport_providers[p_transport] = possible_providers[i];
            p_transport++;
        }
    }
    /* We want to use IMAP as default, since this is the most useful protocol for WebMail */
    config_scheme.setDefaultValue("DEFAULT PROTOCOL", "imap");
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static MimeMessageHelper createEmailMessage(String from, String to)
        throws AddressException, MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    for (String recipient : to.split(";")) {
        email.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }//from www  .j  a va 2 s  . c o m

    return new MimeMessageHelper(email);
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Create a java mail session for a smtp server and port
 * /*from  w ww .  j a v  a2s  .  c o m*/
 * @param smtpServer - server host name
 * @param smtpPort - smtp port
 * @param mailprops - Properties for the mail sender
 * @return instance of java mail session
 */
protected Session createSession(String smtpServer, String smtpPort, Properties mailprops) {
    Properties props = mailprops;
    if (props == null) {
        props = System.getProperties();
    }
    props.put("mail.smtp.host", smtpServer);
    props.setProperty("mail.smtp.port", smtpPort);
    final Session session = Session.getDefaultInstance(props, null);

    return session;
}

From source file:org.apache.camel.component.google.mail.GmailUsersMessagesIntegrationTest.java

private Message createTestEmail() throws MessagingException, IOException {
    com.google.api.services.gmail.model.Profile profile = requestBody(
            "google-mail://users/getProfile?inBody=userId", CURRENT_USERID);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject("Hello from camel-google-mail");
    mm.setContent("Camel rocks!", "text/plain");
    Message createMessageWithEmail = createMessageWithEmail(mm);
    return createMessageWithEmail;
}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

/**
 * Se encarga de enviar el mensaje de correo electronico *
 *//*from  w  w  w . java  2 s . c  o m*/
public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException {
    try {
        Session session;
        Properties properties = System.getProperties();
        properties.put("mail.host", emdto.getHost());
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.port", emdto.getPort());
        properties.put("mail.smtp.starttls.enable", emdto.getStarttls());
        if (emdto.getUser() != null && emdto.getPassword() != null) {
            properties.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emdto.getUser(), emdto.getPassword());
                }
            });
        } else {
            properties.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(properties);
        }

        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask()));
        message.setSubject(emdto.getSubject());

        for (String to : emdto.getToList()) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
        if (emdto.getCcList() != null) {
            for (String cc : emdto.getCcList()) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }
        if (emdto.getCcoList() != null) {
            for (String cco : emdto.getCcoList()) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco));
            }
        }

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage());
        multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (emdto.getFilePaths() != null) {
            for (String filePath : emdto.getFilePaths()) {
                File file = new File(filePath);
                if (file.exists()) {
                    dataSource = new FileDataSource(file);
                    bodyPart = new MimeBodyPart();
                    bodyPart.setDataHandler(new DataHandler(dataSource));
                    bodyPart.setFileName(file.getName());
                    multipart.addBodyPart(bodyPart);
                }
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception",
                ex);
        throw new BusinessException(ex);
    }
    return Boolean.TRUE;
}

From source file:ftpclient.FTPManager.java

public boolean sendUserMail(String uploadedFileName) {
    if (settings != null) {
        try {//from  w w w .  jav a  2s .  c o m
            String userEmail = db.getUserEmail(uid);
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", settings.getSenderEmailHost());
            props.setProperty("mail.smtp.auth", "true");
            //            props.put("mail.smtp.starttls.enable", "true");
            //            props.put("mail.smtp.port", "587");
            Session s = Session.getDefaultInstance(props, new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getSenderLogin(),
                            new String(settings.getSenderPassword()));
                }
            });
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(settings.getSenderEmail());
            msg.addRecipients(Message.RecipientType.TO, userEmail);
            msg.setSubject("FTP action");
            msg.setText("You have succesfully uploaded file " + uploadedFileName);
            Transport.send(msg);
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:com.esri.gpt.framework.mail.MailRequest.java

/**
 * Sends the E-Mail message./*  w  w w  . j  a  va 2  s. co m*/
 * @throws AddressException if an E-Mail address is invalid
 * @throws MessagingException if an exception occurs
 */
public void send() throws AddressException, MessagingException {

    // setup the mail server properties
    Properties props = new Properties();
    props.put("mail.smtp.host", getHost());
    if (getPort() > 0) {
        props.put("mail.smtp.port", "" + getPort());
    }

    // set up the message
    Session session = Session.getDefaultInstance(props, _authenticator);
    Message message = new MimeMessage(session);
    message.setSubject(getSubject());
    message.setContent(getBody(), getMimeType());
    message.setFrom(makeAddress(escapeHtml4(stripControls(getFromAddress()))));
    for (String sTo : getRecipients()) {
        message.addRecipient(Message.RecipientType.TO, makeAddress(sTo));
    }

    // send the message
    Transport.send(message);
}

From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java

/**
 * Instantiate a new session that authenticate given the protocol's properties. Initialize also the default
 * transport protocol handler according to the properties.
 *
 * @since 5.6// w  ww .j a  va 2 s  .c om
 */
public static Session newSession(Properties props) {
    Authenticator authenticator = new EmailAuthenticator(props);
    Session session = Session.getDefaultInstance(props, authenticator);
    String protocol = props.getProperty("mail.transport.protocol");
    if (protocol != null && protocol.length() > 0) {
        session.setProtocolForAddress("rfc822", protocol);
    }
    return session;
}

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  ww  w. j  av a 2  s  .co  m
 * @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:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from   w w w.  j av  a  2 s  . c om*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}