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:Controller.ReadController.java

public ReadController(String gmail_id) throws IOException, MessagingException {

    Message message = MainController.service.users().messages().get("me", gmail_id).setFormat("raw").execute();

    Base64 base64Url = new Base64(true);
    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

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

    MimeMessage mime = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    Email obj = new Email(gmail_id, mime, message.getSnippet());
    this.obj = obj;

    ReadView readView = new ReadView(this, obj);

}

From source file:net.wastl.webmail.authenticators.IMAPSAuthenticator.java

@Override
public void init(Storage store) {
    storage = store;/*  w  w  w. j  av  a  2 s  .  c  o m*/
    final Session session = Session.getDefaultInstance(System.getProperties(), null);
    try {
        st = session.getStore("imaps");
    } catch (final NoSuchProviderException e) {
        log.error("Initialization for 'imaps' failed", e);
    }
}

From source file:net.wastl.webmail.authenticators.POPSAuthenticator.java

@Override
public void init(Storage store) {
    storage = store;/*from  ww  w .java  2 s  .  c  o  m*/
    final Session session = Session.getDefaultInstance(System.getProperties(), null);
    try {
        st = session.getStore("pop3s");
    } catch (final NoSuchProviderException e) {
        log.error("Initialization for 'pop3s' failed", e);
    }
}

From source file:gov.nih.nci.caintegrator.application.mail.SendMail.java

public synchronized void sendMail(String mailTo, String mailCC, String mailBody, String subject)
        throws ValidationException {
    try {//from w w  w. j a  va  2  s .c  o  m
        if (mailTo != null && EmailValidator.getInstance().isValid(mailTo)) {
            //get system properties
            Properties props = System.getProperties();

            String to = mailTo;
            // Set up mail server

            props.put("mail.smtp.host", MailConfig.getInstance(mailProperties).getHost());

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

            //Define Message
            MimeMessage message = new MimeMessage(session);
            MailManager mailManager = new MailManager(mailProperties);
            message.setFrom(new InternetAddress(mailManager.formatFromAddress()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if ((mailCC != null) && EmailValidator.getInstance().isValid(mailCC))
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCC));
            message.setSubject(subject);
            message.setText(mailBody);

            //Send Message

            Transport.send(message);
        } else {
            throw new ValidationException("Invalid Email Address");
        }
    } catch (Exception e) {
        logger.error("Send Mail error", e);
    } //catch
}

From source file:SendMailImpl.java

public void sendMessage(String from, String[] recipients, String subject, String message)
        throws MessagingException {
    boolean debug = false;

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);//w w w.  j  a  va2s .  com

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

@Override
public void handleIncomingEmail(InputStream inputStream) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from  w w w .j  a  v  a  2s.com
        MimeMessage mimeMessage = new MimeMessage(session, inputStream);

        Object messageContent = mimeMessage.getContent();
        String message;
        if (messageContent instanceof Multipart) {
            Multipart mp = (Multipart) messageContent;
            BodyPart bodyPart = mp.getBodyPart(0);
            InputStream is = bodyPart.getInputStream();
            message = convertStreamToString(is);
        } else {
            message = (String) messageContent;
        }

        Address sender = mimeMessage.getFrom()[0];
        final String commandOutput = commandService.process(message, extractEmail(sender.toString()));

        sendResponseMail(sender, commandOutput, mimeMessage.getSubject());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:util.Support.java

/**
 * Send email by SSL/* w ww .  j  a va  2  s  .  c  o m*/
 *
 * @param toEmail Email of user
 * @param idActive id active authentication
 */
public static void sendMail(String toEmail, String idActive) {
    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");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(util.Constants.FROM_EMAIL, util.Constants.PASSWORD_EMAIL);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(util.Constants.FROM_EMAIL));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject("Authentication registration your account.");
        if (!idActive.isEmpty()) {
            message.setText("Dear Mail Crawler," + "\n Click to link to complete the registered , please!"
                    + "\n http://localhost:8084/JudiBlog/active?id=" + idActive + "");
        } else {
            message.setText("OK, thank you!" + "\n You have registed successfully!");
        }
        Transport.send(message);

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

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

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

    try {/*from  w w  w .j  a v  a  2s.c  om*/
        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:org.apache.usergrid.apm.service.util.Mailer.java

public static void send(String recipeintEmail, String subject, String messageText) {
    /*/*from  w w  w . jav a 2s.  c o m*/
     * It is a good practice to put this in a java.util.Properties file and
     * encrypt password. Scroll down to comments below to see how to use
     * java.util.Properties in JSF context.
     */
    Properties props = new Properties();
    try {
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    final String senderEmail = props.getProperty("mail.smtp.sender.email");
    final String smtpUser = props.getProperty("mail.smtp.user");
    final String senderName = props.getProperty("mail.smtp.sender.name");
    final String senderPassword = props.getProperty("senderPassword");
    final String emailtoCC = props.getProperty("instaopsOpsEmailtoCC");

    Session session = Session.getDefaultInstance(props, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUser, senderPassword);
        }
    });
    session.setDebug(false);

    try {
        MimeMessage message = new MimeMessage(session);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(messageText, "text/html");

        // Add message text
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setSubject(subject);
        InternetAddress senderAddress = new InternetAddress(senderEmail, senderName);
        message.setFrom(senderAddress);
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailtoCC));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipeintEmail));
        Transport.send(message);
        log.info("email sent");
    } catch (MessagingException m) {
        log.error(m.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java

@Override
public void processMessages() {
    try {//from   w  w w. j a  va 2 s .  c o m
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message messages[] = folder.search(ft);
            for (Message message : messages) {
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.SEEN), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}