Example usage for javax.mail Message setText

List of usage examples for javax.mail Message setText

Introduction

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

Prototype

public void setText(String text) throws MessagingException;

Source Link

Document

A convenience method that sets the given String as this part's content with a MIME type of "text/plain".

Usage

From source file:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {//from www  . j  a v a 2  s  . c o  m
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:io.kodokojo.service.SmtpEmailSender.java

@Override
public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content,
        boolean htmlContent) {
    if (CollectionUtils.isEmpty(to)) {
        throw new IllegalArgumentException("to must be defined.");
    }//  www  .  ja v  a  2  s . c o m
    if (isBlank(content)) {
        throw new IllegalArgumentException("content must be defined.");
    }
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    try {
        message.setFrom(from);
        message.setSubject(subject);
        InternetAddress[] toInternetAddress = convertToInternetAddress(to);
        message.setRecipients(Message.RecipientType.TO, toInternetAddress);
        if (CollectionUtils.isNotEmpty(cc)) {
            InternetAddress[] ccInternetAddress = convertToInternetAddress(cc);
            message.setRecipients(Message.RecipientType.CC, ccInternetAddress);
        }
        if (CollectionUtils.isNotEmpty(ci)) {
            InternetAddress[] ciInternetAddress = convertToInternetAddress(ci);
            message.setRecipients(Message.RecipientType.BCC, ciInternetAddress);
        }
        if (htmlContent) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        message.setHeader("X-Mailer", "Kodo Kojo mailer");
        message.setSentDate(new Date());
        Transport.send(message);

    } catch (MessagingException e) {
        LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e);
    }
}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails)
        throws UIException, JSONException {

    String token = createToken(csid);
    EmailData ed = spec.getEmailData();/*from   w  w  w  . j a va2 s  .  co m*/
    String[] recipients = new String[1];

    /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */
    String messagebase = ed.getPasswordResetMessage();
    String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam;
    String message = messagebase.replaceAll("\\{\\{link\\}\\}", link);
    String greeting = userdetails.getJSONObject("fields").getString("screenName");
    message = message.replaceAll("\\{\\{greeting\\}\\}", greeting);
    message = message.replaceAll("\\\\n", "\\\n");
    message = message.replaceAll("\\\\r", "\\\r");

    String SMTP_HOST_NAME = ed.getSMTPHost();
    String SMTP_PORT = ed.getSMTPPort();
    String subject = ed.getPasswordResetSubject();
    String from = ed.getFromAddress();
    if (ed.getToAddress().isEmpty()) {
        recipients[0] = emailparam;
    } else {
        recipients[0] = ed.getToAddress();
    }
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", ed.doSMTPAuth());
    props.put("mail.debug", ed.doSMTPDebug());
    props.put("mail.smtp.port", SMTP_PORT);

    Session session = Session.getDefaultInstance(props);
    // XXX fix to allow authpassword /username

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom;
    try {
        addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setText(message);

        Transport.send(msg);
    } catch (AddressException e) {
        throw new UIException("AddressException: " + e.getMessage());
    } catch (MessagingException e) {
        throw new UIException("MessagingException: " + e.getMessage());
    }

    return true;
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    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");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//w w  w.j av a2s .  c o  m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();

    props.setProperty("mail.smtp.host", this.reset.getSmtpServer());
    props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort()));
    props.setProperty("mail.smtp.user", reset.getSmtpUser());
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS()));
    //props.setProperty("mail.debug", "true");
    //props.setProperty("mail.socket.debug", "true");

    if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost());
    }// w  w w  . ja va  2s .  c om

    if (reset.isUseSocks()) {

        props.setProperty("mail.smtp.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort()));
        props.setProperty("mail.smtps.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword());
        }
    });
    //Session session = Session.getInstance(props, null);
    session.setDebugOut(System.out);
    //session.setDebug(true);
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);
    msgToSend.setText(msg.msg);

    msgToSend.saveChanges();
    Transport.send(msgToSend);
    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:EmailBean.java

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;//w  w  w. j av  a2s .c  o m

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null) {

            mailMsg.setFrom(new InternetAddress(from));

        } else {

            throw new MessagingException("The mail message requires a valid 'From' address.");

        }

        if (subject != null)
            mailMsg.setSubject(subject);

        if (content != null)
            mailMsg.setText(content);

        //Finally, send the mail message; throws a 'SendFailedException'
        //if any of the message's recipients have an invalid address
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:it.infn.ct.security.actions.RegisterUser.java

private void sendMail(UserRequest usreq) throws MailException {
    javax.mail.Session session = null;/* w ww  .j  a v  a2  s  .c  om*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        log.error("Mail resource lookup error");
        log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(usreq.getPreferredMail(),
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        String ccMail[] = mailCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_",
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:it.infn.ct.security.utilities.LDAPCleaner.java

private void sendUserRemainder(UserRequest ur, int days) {
    javax.mail.Session session = null;//from  w ww.  j  av a2 s. co m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

        Message mailMsg = new MimeMessage(session);
        mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin")));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(getGoodMail(ur),
                ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) {

            String ccMail[] = rb.getString("mailCopy").split(";");
            InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
            for (int i = 0; i < ccMail.length; i++) {
                mailCCopy[i] = new InternetAddress(ccMail[i]);
            }

            mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);
        }

        if (days > 0) {
            mailMsg.setSubject(
                    rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailNotificationBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        } else {
            mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailDeleteBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        }
        Transport.send(mailMsg);

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
    }
}

From source file:it.infn.ct.security.actions.ActivateAccount.java

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;/*  w w  w .jav a2 s .  co  m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(user.getPreferredMail());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        _log.error("mail bcc: " + mailBCC);
        String ccMail[] = mailBCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.BCC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");
        if (enabled) {
            mailBody = mailBody.replace("_RESULT_", "accepted");
        } else {
            mailBody = mailBody.replace("_RESULT_", "denied");
        }
        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:Mailer.java

/** Send the message.
 *///  ww  w .  j ava2 s. c o m
public synchronized void doSend() throws MessagingException {

    if (!isComplete())
        throw new IllegalArgumentException("doSend called before message was complete");

    /** Properties object used to pass props into the MAIL API */
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);

    // Create the Session object
    if (session == null) {
        session = Session.getDefaultInstance(props, null);
        if (verbose)
            session.setDebug(true); // Verbose!
    }

    // create a message
    final Message mesg = new MimeMessage(session);

    InternetAddress[] addresses;

    // TO Address list
    addresses = new InternetAddress[toList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) toList.get(i));
    mesg.setRecipients(Message.RecipientType.TO, addresses);

    // From Address
    mesg.setFrom(new InternetAddress(from));

    // CC Address list
    addresses = new InternetAddress[ccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) ccList.get(i));
    mesg.setRecipients(Message.RecipientType.CC, addresses);

    // BCC Address list
    addresses = new InternetAddress[bccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) bccList.get(i));
    mesg.setRecipients(Message.RecipientType.BCC, addresses);

    // The Subject
    mesg.setSubject(subject);

    // Now the message body.
    mesg.setText(body);

    // Finally, send the message! (use static Transport method)
    // Do this in a Thread as it sometimes is too slow for JServ
    // new Thread() {
    // public void run() {
    // try {

    Transport.send(mesg);

    // } catch (MessagingException e) {
    // throw new IllegalArgumentException(
    // "Transport.send() threw: " + e.toString());
    // }
    // }
    // }.start();
}