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:com.jvoid.customers.customer.service.CustomerMasterService.java

public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("test@example.com", "test123");
        }/*w w  w  .  j a  v  a2  s.c om*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("toaddress@example.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Reset Password");
        String content = "Your new password is " + password;
        message.setText(content);
        Transport.send(message);

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

From source file:AmazonSESSample.java

private static RawMessage getRawMessage() throws MessagingException, IOException {
    // JavaMail representation of the message
    Session s = Session.getInstance(new Properties(), null);
    s.setDebug(true);/*from w  w w  .j  a v a  2 s  .  c  o  m*/
    MimeMessage msg = new MimeMessage(s);

    // Sender and recipient
    msg.setFrom(new InternetAddress("aravind@gofastpay.com"));
    InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") };
    msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    // Subject
    msg.setSubject(SUBJECT);

    // Add a MIME part to the message
    //MimeMultipart mp = new MimeMultipart();
    Multipart mp = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    //mimeBodyPart.setText(BODY);

    //BodyPart part = new MimeBodyPart();
    //String myText = BODY;
    //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html");
    //part.setText(BODY);
    //mp.addBodyPart(part);
    //msg.setContent(mp);
    mimeBodyPart.setContent(BODY, "text/html");
    mp.addBodyPart(mimeBodyPart);
    msg.setContent(mp);

    // Print the raw email content on the console
    //PrintStream out = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    //String rawString = out.toString();
    //byte[] bytes = IOUtils.toByteArray(msg.getInputStream());
    //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes()));

    //byteBuffer.put(bytes);
    //byteBuffer.put(Base64.getEncoder().encode(bytes));
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray()));
    return rawMessage;
}

From source file:org.kuali.kfs.module.ar.service.impl.AREmailServiceImpl.java

/**
 * This method is used to send emails to the agency
 *
 * @param invoices/*from  w  w w.  j a v a  2  s. c  o  m*/
 */
@Override
public boolean sendInvoicesViaEmail(Collection<ContractsGrantsInvoiceDocument> invoices)
        throws InvalidAddressException, MessagingException {
    LOG.debug("sendInvoicesViaEmail() starting.");

    boolean success = true;
    Properties props = getConfigProperties();

    // Get session
    Session session = Session.getInstance(props, null);
    for (ContractsGrantsInvoiceDocument invoice : invoices) {
        List<InvoiceAddressDetail> invoiceAddressDetails = invoice.getInvoiceAddressDetails();
        for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
            if (ArConstants.InvoiceTransmissionMethod.EMAIL
                    .equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
                Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());

                if (ObjectUtils.isNotNull(note)) {
                    AttachmentMailMessage message = new AttachmentMailMessage();

                    String sender = parameterService.getParameterValueAsString(
                            KFSConstants.OptionalModuleNamespaces.ACCOUNTS_RECEIVABLE,
                            ArConstants.CONTRACTS_GRANTS_INVOICE_COMPONENT, ArConstants.FROM_EMAIL_ADDRESS);
                    message.setFromAddress(sender);

                    CustomerAddress customerAddress = invoiceAddressDetail.getCustomerAddress();
                    String recipients = invoiceAddressDetail.getCustomerEmailAddress();
                    if (StringUtils.isNotEmpty(recipients)) {
                        message.getToAddresses().add(recipients);
                    } else {
                        LOG.warn("No recipients indicated.");
                    }

                    String subject = getSubject(invoice);
                    message.setSubject(subject);
                    if (StringUtils.isEmpty(subject)) {
                        LOG.warn("Empty subject being sent.");
                    }

                    String bodyText = getMessageBody(invoice, customerAddress);
                    message.setMessage(bodyText);
                    if (StringUtils.isEmpty(bodyText)) {
                        LOG.warn("Empty bodyText being sent.");
                    }

                    Attachment attachment = note.getAttachment();
                    if (ObjectUtils.isNotNull(attachment)) {
                        try {
                            message.setContent(IOUtils.toByteArray(attachment.getAttachmentContents()));
                        } catch (IOException ex) {
                            LOG.error("Error setting attachment contents", ex);
                            throw new RuntimeException(ex);
                        }
                        message.setFileName(attachment.getAttachmentFileName());
                        message.setType(attachment.getAttachmentMimeTypeCode());
                    }

                    setupMailServiceForNonProductionInstance();
                    mailService.sendMessage(message);

                    invoiceAddressDetail.setInitialTransmissionDate(new Date(new java.util.Date().getTime()));
                    documentService.updateDocument(invoice);
                } else {
                    success = false;
                }
            }
        }
    }
    return success;
}

From source file:org.tomitribe.tribestream.registryng.service.monitoring.MailAlerter.java

@PostConstruct
private void init() {
    active = active && to != null;
    if (!active) {
        return;//from w w w.ja  v  a 2  s. c o  m
    }

    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        hostname = "unknown";
    }

    final Properties properties = new Properties();
    properties.setProperty("mail.transport.protocol", transport);
    properties.setProperty("mail." + transport + ".host", host);
    properties.setProperty("mail." + transport + ".port", Integer.toString(port));
    if (tls) {
        properties.setProperty("mail." + transport + ".starttls.enable", "true");
    }
    if (user != null) {
        properties.setProperty("mail." + transport + ".user", user);
    }
    if (password != null) {
        properties.setProperty("password", password);
    }
    if (auth || password != null) {
        properties.setProperty("mail." + transport + ".auth", "true");
    }
    if (timeout > 0) {
        properties.setProperty("mail." + transport + ".timeout", Integer.toString(timeout));
    }

    if (password != null) {
        final PasswordAuthentication pa = new PasswordAuthentication(user, password);
        session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return pa;
            }
        });
    } else {
        session = Session.getInstance(properties);
    }
}

From source file:com.huffingtonpost.chronos.servlet.TestConfig.java

@Bean
public Session authSession() {
    final String username = "spluh";
    final String password = "abracaduh";
    Session session = Session.getInstance(authMailProperties(), new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* w w w. j ava2s  . c om*/
    });
    return session;
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//  ww  w .j a v  a 2  s .c  o m
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.app.mail.DefaultMailSender.java

private static Session _authenticateOutboundEmailAddress() {
    return Session.getInstance(PropertiesUtil.getConfigurationProperties(), new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(PropertiesValues.OUTBOUND_EMAIL_ADDRESS,
                    PropertiesValues.OUTBOUND_EMAIL_ADDRESS_PASSWORD);
        }//  w  ww .j a  v a2s .  c  om

    });
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

public Session getSession() {
    if (session == null) {
        synchronized (this) {
            if (session == null) {
                if (sessionName != null) {
                    try {
                        InitialContext ic = new InitialContext();
                        session = (Session) ic.lookup(sessionName);
                    } catch (NamingException e) {
                        log.warn("Failed to lookup mail session using JNDI name " + sessionName
                                + ". Falling back on local configuration.");
                        session = Session.getInstance(config, auth);
                    }/*from w  w  w .j a  va 2  s.co m*/
                } else {
                    session = Session.getInstance(config, auth);
                }
            }
        }
    }
    return session;
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private Session buildSession() {

    final Properties props = new Properties();

    try {//from   w ww  .  j a v  a 2 s.  c om
        final Document configDocument = PentahoSystem.getSystemSettings()
                .getSystemSettingsDocument("smtp-email/email_config.xml"); //$NON-NLS-1$
        final List<Node> properties = configDocument.selectNodes("/email-smtp/properties/*"); //$NON-NLS-1$
        for (Node propertyNode : properties) {
            final String propertyName = propertyNode.getName();
            final String propertyValue = propertyNode.getText();
            props.put(propertyName, propertyValue);
        }
    } catch (Exception e) {
        logger.error("Failed to build session: " + e.getMessage());
    }

    final boolean authenticate = "true".equals(props.getProperty("mail.smtp.auth")); //$NON-NLS-1$//$NON-NLS-2$

    // Get a Session object

    final Session session;
    if (authenticate) {
        final Authenticator authenticator = new EmailAuthenticator();
        session = Session.getInstance(props, authenticator);
    } else {
        session = Session.getInstance(props);
    }

    // if debugging is not set in the email config file, match the
    // component debug setting
    if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
        session.setDebug(true);
    }

    return session;

}

From source file:io.mapzone.arena.EMailHelpDashlet.java

protected void initMailSession() {
    Properties props = new Properties();
    props.put("mail.smtp.host", System.getProperty("mail.smtp.host", smtpHost.get()));
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.auth", "true");
    // TODO uncomment if the mail server contains a correct SSL certificate
    // props.put( "mail.smtp.starttls.enable", "true" ); // enable STARTTLS

    // create Authenticator object to pass in Session.getInstance argument
    Authenticator auth = new Authenticator() {
        @Override/*ww w  .j a  va2 s .  c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUser.get(), smtpPassword.get());
        }
    };
    assert session == null;
    session = Session.getInstance(props, auth);
}