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:com.angstoverseer.service.mail.MailServiceImpl.java

private void sendResponseMail(final Address sender, final String answer, final String subject)
        throws Exception {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("overseer@thenewoverseer.appspotmail.com", "Overseer"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sender.toString()));
    mimeMessage.setSubject("Re: " + subject);
    mimeMessage.setText(answer);//ww w  .  j  av  a2 s.co  m
    Transport.send(mimeMessage);
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * Store general propreties (mailJet), create session and addressFrom
 *
 * @param mapConfigEmail/*from ww  w .j  ava2  s. c om*/
 * @return
 * @throws AddressException
 * @throws MessagingException
 */
private Map<String, Object> initEmailConfig(Map<String, Object> mapConfigEmail)
        throws AddressException, MessagingException {

    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(this.getClass(), "/fr.treeptik.cloudunit.templates/");

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.socketFactory.port", socketFactoryPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", smtpPort);

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(apiKey, secretKey);
        }
    });

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(emailFrom));

    mapConfigEmail.put("message", message);
    mapConfigEmail.put("configuration", configuration);

    return mapConfigEmail;

}

From source file:ru.org.linux.user.LostPasswordController.java

private void sendEmail(User user, String email, Timestamp resetDate) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    String resetCode = UserService.getResetCode(configuration.getSecret(), user.getNick(), email, resetDate);

    msg.addRecipient(RecipientType.TO, new InternetAddress(email));
    msg.setSubject("Your password @linux.org.ru");
    msg.setSentDate(new Date());
    msg.setText("?!\n\n"
            + "? ??  ?   ?? http://www.linux.org.ru/reset-password\n\n"
            + "  " + user.getNick() + ",  ?: " + resetCode + "\n\n"
            + "!");

    Transport.send(msg);/*w  ww  . j  a  va 2s.c o  m*/
}

From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }/* w  ww . j av  a 2  s. c o m*/
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}

From source file:cc.kune.core.server.mail.MailServiceDefault.java

@Override
public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body,
        final boolean isHtml, final String... tos) {
    if (smtpSkip) {
        return;/*from   ww  w  . j  a va  2s . co m*/
    }

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

    // Define message
    final MimeMessage message = new MimeMessage(session);
    for (final String to : tos) {
        try {
            message.setFrom(new InternetAddress(from));
            // In case we should use utf8 also in address:
            // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // If additional header should be added
            // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
            final String formatedSubject = subject.getString();
            message.setSubject(formatedSubject, "utf-8");
            final String formatedBody = body.getString();
            if (isHtml) {
                // message.setContent(formatedBody, "text/html");
                message.setText(formatedBody, "UTF-8", "html");
            } else {
                message.setText(formatedBody, "UTF-8");
            }
            // Send message
            Transport.send(message);
        } catch (final AddressException e) {
        } catch (final MessagingException e) {
            final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s",
                    from, subject, to);
            log.error(error, e);
            // Better not to throw exceptions because users emails can be wrong...
            // throw new DefaultException(error, e);
        }
    }
}

From source file:org.wandora.piccolo.actions.SendEmail.java

public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response,
        Application application) {//from w w w .j  a v  a  2  s. co  m
    try {

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

        MimeMessage message = new MimeMessage(session);
        if (subject != null)
            message.setSubject(subject);
        if (from != null)
            message.setFrom(new InternetAddress(from));
        Vector<String> recipients = new Vector<String>();
        if (recipient != null) {
            String[] rs = recipient.split(",");
            String r = null;
            for (int i = 0; i < rs.length; i++) {
                r = rs[i];
                if (r != null)
                    recipients.add(r);
            }
        }

        MimeMultipart multipart = new MimeMultipart();

        Template template = application.getTemplate(emailTemplate, user);
        HashMap context = new HashMap();
        context.put("request", request);
        context.put("message", message);
        context.put("recipients", recipients);
        context.put("emailhelper", new MailHelper());
        context.put("multipart", multipart);
        context.putAll(application.getDefaultContext(user));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        template.process(context, baos);

        MimeBodyPart mimeBody = new MimeBodyPart();
        mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType());
        //            mimeBody.setContent(baos.toByteArray(),template.getMimeType());
        multipart.addBodyPart(mimeBody);
        message.setContent(multipart);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpServer, smtpUser, smtpPass);
        Address[] recipientAddresses = new Address[recipients.size()];
        for (int i = 0; i < recipientAddresses.length; i++) {
            recipientAddresses[i] = new InternetAddress(recipients.elementAt(i));
        }
        transport.sendMessage(message, recipientAddresses);
    } catch (Exception e) {
        logger.writelog("WRN", e);
    }
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

public synchronized static Message[] readAll(String protocol, String server, int securityConnection, int port,
        String user, String password, boolean onlyUnreadMessages) {
    Message[] msgs = null;/*from  www  .  j  a va2s .c om*/
    try {
        Properties props = System.getProperties();
        updateSecurityProps(protocol, server, securityConnection, props);
        Session session = Session.getDefaultInstance(props, null);

        if (LOGGER.isDebugEnabled()) {
            session.setDebug(true);
        } else {
            session.setDebug(false);
        }

        // instantiate POP3-store and connect to server
        store = session.getStore(protocol);
        boolean connected = SyncStore.connect(store, protocol, server, port, user, password);
        if (!connected) {
            return msgs;
        }
        connPoint = SyncStore.getConnPoint(store, protocol, server, port, user, password);
        store = connPoint.getStore();

        // access default folder
        folder = store.getDefaultFolder();

        // can't find default folder
        if (folder == null) {
            throw new Exception("No default folder");
        }

        // messages are always in folder INBOX
        folder = folder.getFolder("INBOX");

        // can't find INBOX
        if (folder == null) {
            throw new Exception("No POP3 INBOX");
        }

        // open folder
        folder.open(Folder.READ_WRITE);

        // retrieve messages
        if (onlyUnreadMessages) {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            msgs = folder.search(ft);
        } else {
            msgs = folder.getMessages();
        }
    } catch (Exception ex) {
        if (LogThrottle.isReady("MailReader1", 240)) {
            LOGGER.error(ExceptionUtils.getStackTrace(ex));
        }
    }
    return msgs;
}

From source file:com.tdclighthouse.commons.mail.util.MailClient.java

private Session getSession() {
    if (session == null) {
        // Setup mail server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailServer);
        if (portNumber > 0) {
            props.put("mail.smtp.port", portNumber);
        }/*from  w ww  .  j a v  a2s .  c o m*/

        // Get a mail session
        session = Session.getDefaultInstance(props, null);
    }
    return session;
}

From source file:org.apache.axis.transport.mail.MailServer.java

/**
 * Accept requests from a given TCP port and send them through the
 * Axis engine for processing.// ww  w  . java2s.  c  om
 */
public void run() {
    log.info(Messages.getMessage("start00", "MailServer", host + ":" + port));

    // Accept and process requests from the socket
    while (!stopped) {
        try {
            pop3.connect(host, port);
            pop3.login(userid, password);

            POP3MessageInfo[] messages = pop3.listMessages();
            if (messages != null && messages.length > 0) {
                for (int i = 0; i < messages.length; i++) {
                    Reader reader = pop3.retrieveMessage(messages[i].number);
                    if (reader == null) {
                        continue;
                    }

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

                    MimeMessage mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[i].number);
                    if (mimeMsg != null) {
                        MailWorker worker = new MailWorker(this, mimeMsg);
                        if (doThreads) {
                            Thread thread = new Thread(worker);
                            thread.setDaemon(true);
                            thread.start();
                        } else {
                            worker.run();
                        }
                    }
                }
            }
        } catch (java.io.InterruptedIOException iie) {
        } catch (Exception e) {
            log.debug(Messages.getMessage("exception00"), e);
            break;
        } finally {
            try {
                pop3.logout();
                pop3.disconnect();
                Thread.sleep(3000);
            } catch (Exception e) {
                log.error(Messages.getMessage("exception00"), e);
            }
        }
    }
    log.info(Messages.getMessage("quit00", "MailServer"));
}

From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java

@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) {
        // Get the email properties entered via Share Form
        String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME);
        String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME);
        String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME);

        // Get document filename
        Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef,
                ContentModel.PROP_NAME);
        if (filename == null) {
            throw new AlfrescoRuntimeException("Document filename is null");
        }/*w  w w  . j a  v a  2s.  c om*/
        String documentName = (String) filename;

        try {
            // Create mail session
            Properties mailServerProperties = new Properties();
            mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.host", "localhost");
            mailServerProperties.put("mail.smtp.port", "2525");
            Session session = Session.getDefaultInstance(mailServerProperties, null);
            session.setDebug(false);

            // Define message
            Message message = new MimeMessage(session);
            String fromAddress = "training@alfresco.com";
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Create the message part with body text
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the Attachment part
            //
            //  Get the document content bytes
            byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName);
            if (documentData == null) {
                throw new AlfrescoRuntimeException("Document content is null");
            }
            //  Attach document
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData,
                    new MimetypesFileTypeMap().getContentType(documentName))));
            messageBodyPart.setFileName(documentName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send mail
            Transport.send(message);

            // Set status on node as "sent via email"
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
            properties.put(ContentModel.PROP_ORIGINATOR, fromAddress);
            properties.put(ContentModel.PROP_ADDRESSEE, to);
            properties.put(ContentModel.PROP_SUBJECT, subject);
            properties.put(ContentModel.PROP_SENTDATE, new Date());
            serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED,
                    properties);
        } catch (MessagingException me) {
            me.printStackTrace();
            throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage());
        }
    }
}