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:org.apache.axis.transport.mail.MailSender.java

/**
 * Read from server using POP3/*ww w.ja v  a2  s .  com*/
 * @param msgContext
 * @throws Exception
 */
private void readUsingPOP3(String id, MessageContext msgContext) throws Exception {
    // Read the response back from the server
    String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
    String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
    String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);

    Reader reader;
    POP3MessageInfo[] messages = null;

    MimeMessage mimeMsg = null;
    POP3Client pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    for (int i = 0; i < 12; i++) {
        pop3.connect(pop3Host);

        if (!pop3.login(pop3User, pop3passwd)) {
            pop3.disconnect();
            AxisFault fault = new AxisFault("POP3", "( Could not login to server.  Check password. )", null,
                    null);
            throw fault;
        }

        messages = pop3.listMessages();
        if (messages != null && messages.length > 0) {
            StringBuffer buffer = null;
            for (int j = 0; j < messages.length; j++) {
                reader = pop3.retrieveMessage(messages[j].number);
                if (reader == null) {
                    AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null,
                            null);
                    throw fault;
                }

                buffer = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(reader);
                int ch;
                while ((ch = bufferedReader.read()) != -1) {
                    buffer.append((char) ch);
                }
                bufferedReader.close();
                if (buffer.toString().indexOf(id) != -1) {
                    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes());
                    Properties prop = new Properties();
                    Session session = Session.getDefaultInstance(prop, null);

                    mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[j].number);
                    break;
                }
                buffer = null;
            }
        }
        pop3.logout();
        pop3.disconnect();
        if (mimeMsg == null) {
            Thread.sleep(5000);
        } else {
            break;
        }
    }

    if (mimeMsg == null) {
        pop3.logout();
        pop3.disconnect();
        AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
        throw fault;
    }

    String contentType = mimeMsg.getContentType();
    String contentLocation = mimeMsg.getContentID();
    Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation);

    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPPartAsString());
    }
}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

protected void sendEmail(EmailConfiguration config, String recipientAddress, String subject, String body) {
    String mailHost = config.getMailServer();
    Boolean mailUseSMTPS = config.isSMTPS();
    String mailUser = config.getUsername();
    String mailPassword = config.getPassword();

    if (mailHost == null) {
        throw new HobsonRuntimeException("No mail host is configured; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailUser == null) {
        throw new HobsonRuntimeException(
                "No mail server username is configured for SMTPS; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailPassword == null) {
        throw new HobsonRuntimeException(
                "No mail server password is configured for SMTPS; unable to execute e-mail action");
    }/*from  ww  w .j a va  2s . c o  m*/

    // create mail session
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);
    Session session = Session.getDefaultInstance(props, null);

    // create the mail message
    Message msg = createMessage(session, config, recipientAddress, subject, body);

    // send the message
    String protocol = mailUseSMTPS ? "smtps" : "smtp";
    int port = mailUseSMTPS ? 465 : 25;
    try {
        Transport transport = session.getTransport(protocol);
        logger.debug("Sending e-mail to {} using {}@{}:{}", msg.getAllRecipients(), mailUser, mailHost, port);
        transport.connect(mailHost, port, mailUser, mailPassword);
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        logger.debug("Message sent successfully");
    } catch (MessagingException e) {
        logger.error("Error sending e-mail message", e);
        throw new HobsonRuntimeException("Error sending e-mail message", e);
    }
}

From source file:org.wso2.es.ui.integration.util.ESUtil.java

/**
 * To check if a e-mail exists with a given subject
 *
 * @param smtpPropertyFile smtp property file path
 * @param password         password//from   w  w  w  . j  a  va  2  s  .  c  o m
 * @param email            email address
 * @param subject          email subject
 * @return if the mail exist
 * @throws java.io.IOException
 * @throws MessagingException
 * @throws InterruptedException
 */
public static String readEmail(String smtpPropertyFile, String password, String email, String subject)
        throws MessagingException, InterruptedException, IOException {
    Properties props = new Properties();
    String message = null;
    Folder inbox = null;
    Store store = null;
    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(new File(smtpPropertyFile));
        props.load(inputStream);
        Session session = Session.getDefaultInstance(props, null);
        store = session.getStore(IMAPS);
        store.connect(SMTP_GMAIL_COM, email, password);
        inbox = store.getFolder(INBOX);
        inbox.open(Folder.READ_ONLY);
        message = getMailWithSubject(inbox, subject);
    } catch (MessagingException e) {
        LOG.error(getErrorMessage(email), e);
        throw e;
    } catch (InterruptedException e) {
        LOG.error(getErrorMessage(email), e);
        throw e;
    } catch (FileNotFoundException e) {
        LOG.error(getErrorMessage(email), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getErrorMessage(email), e);
        throw e;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error("Input stream closing failed");
            }
        }
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                LOG.error("Inbox closing failed");
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                LOG.error("Message store closing failed");
            }
        }
    }
    return message;
}

From source file:com.netspective.commons.message.SendMail.java

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

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

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }//from  w  w w .  j  av  a2 s  .  c o  m
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {
    //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");
        }/* w ww. jav  a  2  s .  c om*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        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);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

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

}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public void sendEmail(String to, String subject, String body) {
    final String fromUser = fromMail;
    final String passUser = password;
    Properties props = new Properties();
    props.put("mail.smtp.host", smtp);
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.auth", mailAuth);
    props.put("mail.smtp.port", port);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromUser, passUser);
        }//  w ww .  j a  va  2  s  .  c om
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromUser));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public correoNoLeidos ltaRecibidos2(String name, int num) {
    correoNoLeidos lta = new correoNoLeidos();
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {/*  w ww  .j  a  v  a  2 s .  c o  m*/
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                if (num == message.getMessageNumber()) {
                    //message.setFlag(Flags.Flag.SEEN, true);
                    lta.setNum(message.getMessageNumber());
                    lta.setFecha(message.getSentDate().toString());
                    lta.setDe(message.getFrom()[0].toString());
                    lta.setAsunto(message.getSubject().toString());
                    correoNoLeidos co = new correoNoLeidos();
                    List<String> arc = new ArrayList<String>();
                    List<String> rar = new ArrayList<String>();
                    correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message);
                    lta.setImagenes(cc.getImagenes());
                    lta.setRar(cc.getRar());
                    lta.setContenido(cc.getContenido());
                    String cont = "";

                    String contenido = "";

                    //lta.setContenido(analizaParteDeMensaje2(message));
                }
            } catch (Exception e) {
                System.out.println("No Information");
            }

        }
    } catch (MessagingException e) {
        System.out.println(e.toString());
    }

    return lta;
}

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

/**
 * This method does the actual initialisation
 *///from  w ww. java2 s. co m
protected void doInit(WebMailServer parent, HTTPRequestHeader h)
        throws UserDataException, InvalidPasswordException, WebMailException {
    String domain;
    setLastAccess();
    this.parent = parent;
    remote_agent = h.getHeader("User-Agent").replace('\n', ' ');
    remote_accepts = h.getHeader("Accept").replace('\n', ' ');
    log.info("WebMail: New Session (" + session_code + ")");
    if (parent.getStorage().getVirtuals() == true && h.getContent("vdom") != null) {
        domain = h.getContent("vdom");
    } else {
        domain = "localnet";
    }
    user = WebMailServer.getStorage().getUserData(h.getContent("login"), domain, h.getContent("password"),
            true);
    last_login = user.getLastLogin();
    user.login();
    login_password = h.getContent("password");
    model = parent.getStorage().createXMLUserModel(user);
    connections = new Hashtable<String, Folder>();
    stores = new Hashtable<String, Store>();
    folders = new Hashtable<String, Folder>();
    mailsession = Session.getDefaultInstance(System.getProperties(), null);

    /* If the user logs in for the first time we want all folders subscribed */
    /* // Nope, we don't want that!
    if(user.getLoginCount().equals("1")) {
    Enumeration enumVar=user.mailHosts();
    while(enumVar.hasMoreElements()) {
        String id=(String)enumVar.nextElement();
        if(user.getMailHost(id).getName().equals("Default")) {
            try {
                setSubscribedAll(id,true);
            } catch(MessagingException ex) {
                ex.printStackTrace();
            }
            break;
        }
    }
    }
    */
    setEnv();
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//from w  w  w . j  a v a  2s .co m
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * ????/*ww  w  .ja v  a 2  s  .  c o  m*/
 *
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
public void execute() throws UnsupportedEncodingException, MessagingException {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    final MimeMessage message = new MimeMessage(session);

    message.setFrom(fromAddress.toInternetAddress(charset));
    message.setReplyTo(toInternetAddresses(replyToAddressList));
    message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList));
    message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList));
    message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList));
    message.setSubject(subject, charset);

    setContent(message);

    message.setSentDate(new Date());

    Transport.send(message);
}