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:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from   ww  w .j  a  v a  2 s .  co  m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}

From source file:com.gazbert.bxbot.core.mail.EmailAlerter.java

public void sendMessage(String subject, String msgContent) {

    if (sendEmailAlertsEnabled) {

        final Session session = Session.getInstance(smtpProps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpConfig.getAccountUsername(),
                        smtpConfig.getAccountPassword());
            }//from  w ww  . j ava2s  . co  m
        });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(smtpConfig.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpConfig.getToAddress()));
            message.setSubject(subject);
            message.setText(msgContent);

            LOG.info(() -> "About to send following Email Alert with message content: " + msgContent);
            Transport.send(message);

        } catch (MessagingException e) {
            // not much we can do here, especially if the alert was critical - the bot is shutting down; just log it.
            LOG.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
        }
    } else {
        LOG.warn("Email Alerts are disabled. Not sending the following message: Subject: " + subject
                + " Content: " + msgContent);
    }
}

From source file:de.fzi.ALERT.actor.ActionActuator.MailService.java

public void sendEmail(Authenticator auth, String address, String subject, String content) {
    try {/*from  w ww  .j a  v a 2 s  . c om*/
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, auth);
        // -- Create a new message --
        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // -- Set the subject and body text --
        msg.setSubject(subject);
        msg.setText(content);

        // -- Set some other header information --
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());

        // -- Send the message --
        Transport.send(msg);

        System.out.println("An announce Mail has been send to " + address);
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.freemarker.mail.GMail.java

public boolean sendMailUsingJavaMailAPI(String to, String message1, HttpServletRequest req, String mid,
        String createdby, String pname, String mname) {
    String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateDataMapping(message1,
            getTemplateLocation(req), mid, createdby, pname, mname);
    String from = "analytixdstest@gmail.com";
    final String username = "analytixdstest@gmail.com";
    final String password = "analytix000";
    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");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from  w ww . j a v  a  2 s  .  c  om*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setContent(FinalMessage, "text/html; charset=utf-8");
        message.saveChanges();
        message.setSubject("Analytix Test Mail");
        Transport.send(message);
        return true;
    } catch (MessagingException e) {
        return false;

    }
}

From source file:Security.EmailSender.java

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *//* w w w  .  j  a  v  a2  s .  co  m*/
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    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("Confirmation email from GPSWebApp server!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from GPSWebApp server!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8084/GPSWebApp/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

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

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

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

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *///w  ww  . j  a v a 2  s  . c o m
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    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("Confirmation email from gTraxxx app!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from gTraxxx app!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8080/gTraxxx/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

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

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

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);
        }/*from w  ww. j ava2  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:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    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() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*from w  w w .  j a  va 2 s  .  c  om*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

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

From source file:Security.EmailSender.java

/**
 * Metda sendUserPasswordRecoveryEmail je ur?en na generovbanie a zaslanie pouvateovi email s obnovenm jeho zabudnutho hesla.
 * @param email - pouvatesk email/*from w  ww  .j  ava  2 s  .  co m*/
 */
public void sendUserPasswordRecoveryEmail(String email) {
    try {
        DBLoginFinder finder = new DBLoginFinder();
        ArrayList<String> results = finder.getUserInformation(email);
        String name = "NONE";
        String surname = "NONE";
        if (results.get(0) != null) {
            name = results.get(0);
        }
        if (results.get(1) != null) {
            surname = results.get(1);
        }

        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>" + results.get(5)
                    + "</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:webreader.WebReader.java

private void sendEmail(String inputMessage) {
    //---User login information
    final String username = email;
    final String password = emailPassword;

    //---Sets server for gmail
    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");

    //---Creates a new session
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);

        }//w  w  w  . ja v a  2  s.  c  o  m

    });
    //---Try catch loop for sending an email
    //---Sends error email to the sender if catch is engaged.
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject("Your grades have been updated");
        message.setText(inputMessage);
        Transport.send(message);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        emailSent = "E-mail was sent: " + dateFormat.format(date);
        System.out.println(emailSent);
    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //---Used code from https://www.youtube.com/watch?v=sHC8YgW21ho
    //---for the above method
}