Example usage for javax.mail Message setSubject

List of usage examples for javax.mail Message setSubject

Introduction

In this page you can find the example usage for javax.mail Message setSubject.

Prototype

public abstract void setSubject(String subject) throws MessagingException;

Source Link

Document

Set the subject of this message.

Usage

From source file:com.bizintelapps.cars.service.impl.EmailServiceImpl.java

/**
 * /*  ww  w  .  ja va  2 s.  c  o  m*/
 * @param recipients
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, Car car, String comment) {

    try {
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {

                addressTo[i] = new InternetAddress(recipients[i]);

            }
        }

        if (addressTo == null || addressTo.length == 0) {
            return;
        }

        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_FROM_USERNAME, SEND_FROM_PASSWORD);
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(EMAIL_FROM_ADDRESS);
        msg.setFrom(addressFrom);
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        String message = buildMessage(car, comment);
        msg.setContent(message, EMAIL_CONTENT_TYPE);

        Transport.send(msg);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Error sending email, please check to and from emails are correct!");
    }
}

From source file:sk.mlp.security.EmailSender.java

/**
 * Metda sendUserPasswordRecoveryEmail je ur?en na generovbanie a zaslanie pouvateovi email s obnovenm jeho zabudnutho hesla.
 * @param email - pouvatesk email//from   ww w  .  j  av a 2  s . c o m
 */
public void sendUserPasswordRecoveryEmail(String email) {
    try {
        DatabaseServices databaseServices = new DatabaseServices();
        User user = databaseServices.findUserByEmail(email);
        String name = "NONE";
        String surname = "NONE";
        if (user.getFirstName() != null) {
            name = user.getFirstName();
        }
        if (user.getLastName() != null) {
            surname = user.getLastName();
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", server);
        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() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Your password to GPSWebApp server!!!");
            //message.setText(userToken);
            message.setSubject("Your password to GPSWebApp server!!!");
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname + ",</h1><br>your paassword to access GPSWebApp server is <b>" + user.getPass()
                    + "</b>. <br>Please take note that you can change it in your settings. Have a pleasant day.</body></html>",
                    "text/html");

            Transport.send(message);

            FileLogger.getInstance()
                    .createNewLog("Successfuly sent password recovery email to user " + email + ".");

        } catch (MessagingException e) {
            FileLogger.getInstance()
                    .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
        }
    } catch (Exception ex) {
        FileLogger.getInstance()
                .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
    }
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Send mail to the given email id with the provided text and subject.
 * //w  ww  . j  av a 2s  . c  om
 * @param recepientEmailId email id of the recepient
 * @param emailText text of the mail
 * @param subject subject of the mail
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 */
protected void sendMail(String recepientEmailId, String emailText, String subject)
        throws IdeasExchangeException, AddressException, MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    Message message = new MimeMessage(session);

    message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId));
    message.setFrom(new InternetAddress(getAdminMailId()));

    message.setText(emailText);
    message.setSubject(subject);

    Transport.send(message);
    log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject);
}

From source file:org.openengsb.connector.email.internal.abstraction.JavaxMailAbstraction.java

@Override
public void send(MailProperties properties, String subject, String textContent, String receiver) {
    try {/*from   w  ww. j a  v a2 s .  c o m*/
        if (!(properties instanceof MailPropertiesImp)) {
            throw new RuntimeException("This implementation works only with internal mail properties");
        }
        MailPropertiesImp props = (MailPropertiesImp) properties;

        Session session = getSession(props);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(props.getSender()));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(receiver));
        message.setSubject(buildSubject(props, subject));
        message.setText(textContent);
        send(message, session);
    } catch (Exception e) {
        throw new DomainMethodExecutionException(e);
    }
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }// www.jav a  2s  .com
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:mupomat.view.PodrskaLozinka.java

private void posaljiEmail() {

    final String username = "mupomat@gmail.com";
    final String password = "lesnibokysr187";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override/*  w w w. ja va 2  s.com*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("mupomat@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtEmail.getText().trim()));
        message.setSubject("MUPomat podrka");

        message.setText("Nova lozinka: " + generiranaLozinka
                + "\nMolimo Vas da nakon prijave promjenite lozinku radi sigurnosti.\nHvala.");

        Transport.send(message);
        this.dispose();
        JOptionPane.showMessageDialog(rootPane, "Lozinka je uspjeno poslana na Vau e-mail adresu!",
                "MUPomat: Podrka", JOptionPane.INFORMATION_MESSAGE);

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

}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 *
 *///ww w  .  j  ava2 s.  c om
private Message createMessage(String from, String to, String subject, String content) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);

        message.setContent(content, "text/html");
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        message.setSubject(subject);
        message.setText(content);
        message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:Utilities.SendEmailUsingGMailSMTP.java

public void enviarCorreo(String correo, String clave) {
    String to = correo;//from  w  w  w .  j ava2  s  . co  m

    final String username = "angelicabarrientosvera@gmail.com";//change accordingly
    final String password = "90445359D10s";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(to));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Testing Subject");

        // Now set the actual message
        message.setText("\n" + "Use esta clave para poder restablecer la contrasea" + "\n"
                + "Tu cdigo para restaurar su cuenta es:" + clave);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");
        //return true;

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

    }

}

From source file:se.vgregion.mobile.services.SmtpErrorReportService.java

@Override
public void report(ErrorReport report) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    try {/*from   w ww . java  2 s. c  o m*/
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);

        String text = String.format(body, report.getPrinter().getName(), report.getDescription(),
                report.getReporter());
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("Failed sending error report via mail", e);
    }

}

From source file:org.mot.common.tools.EmailFactory.java

public void sendEmail(String recipient, String subject, String body) {

    if (enabled) {

        try {//from  w w  w  . ja v a 2 s. c o m

            if (recipient == null || recipient == "") {
                recipient = rcpt;
            }

            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

            // Set Subject: header field
            message.setSubject(subject);

            // Send the actual HTML message, as big as you like
            message.setText(body);

            // Send message
            Transport.send(message);
            //System.out.println("Sent message successfully....");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}