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:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

/**
 * Fill the body of a message already created.
 * The result message depends on the information given.
 *
 * @param message/*from w w w  .j a v a 2  s. c  o m*/
 * @param text
 * @param html
 * @param parts
 * @return The composed message
 * @throws MessagingException
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
public static Message composeMessage(Message message, String text, String html, List parts)
        throws MessagingException, IOException {

    MimeBodyPart txtPart = null;
    MimeBodyPart htmlPart = null;
    MimeMultipart mimeMultipart = null;

    if (text == null && html == null) {
        text = "";
    }
    if (text != null) {
        txtPart = new MimeBodyPart();
        txtPart.setContent(text, "text/plain; charset=UTF-8");
    }
    if (html != null) {
        htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html; charset=UTF-8");
    }
    if (html != null && text != null) {
        mimeMultipart = new MimeMultipart();
        mimeMultipart.setSubType("alternative");
        mimeMultipart.addBodyPart(txtPart);
        mimeMultipart.addBodyPart(htmlPart);
    }

    if (parts == null || parts.isEmpty()) {
        if (mimeMultipart != null) {
            message.setContent(mimeMultipart);
        } else if (html != null) {
            message.setText(html);
            message.setHeader("Content-type", "text/html");
        } else if (text != null) {
            message.setText(text);
        }
    } else {
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (mimeMultipart != null) {
            bodyPart.setContent(mimeMultipart);
        } else if (html != null) {
            bodyPart.setText(html);
            bodyPart.setHeader("Content-type", "text/html");
        } else if (text != null) {
            bodyPart.setText(text);
        }
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
        for (Object attachment : parts) {
            if (attachment instanceof FileItem) {
                multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment));
            } else {
                multipart.addBodyPart((BodyPart) attachment);
            }
        }
        message.setContent(multipart);
    }

    message.saveChanges();
    return message;

}

From source file:org.nuxeo.ecm.platform.mail.action.SendMailAction.java

public boolean execute(ExecutionContext context) throws MessagingException {
    Message message = context.getMessage();
    if (log.isDebugEnabled()) {
        log.debug("Sending mail because of message: " + message.getSubject());
    }//w w w. j a  v  a2s . c  om
    Message sentMessage = new MimeMessage(session);
    if (message.getReplyTo() == null || message.getReplyTo().length == 0) {
        return true;
    }
    Address address = message.getReplyTo()[0];
    sentMessage.setRecipient(Message.RecipientType.TO, address);
    message.setText(textMessage);
    Transport.send(sentMessage);
    return true;
}

From source file:domain.Employee.java

private String newPassword(String email) {

    if (email.equals("")) {
        throw new IllegalArgumentException("email must not be null");
    }/*from   w  ww.  ja  v  a  2s.c o  m*/
    String pass = RandomStringUtils.randomAlphanumeric(8);
    //email the employee the password they can use to login

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String messagebody = String.format(
            "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n"
                    + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration",
            getName(), getEmail(), pass);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName()));
        msg.setSubject("Your account has been activated");
        msg.setText(messagebody);
        Transport.send(msg);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
    //hash the string and set the employee's password to the hashed one. USED SHA256
    System.out.println(pass);
    String hash = DigestUtils.sha256Hex(pass);
    return hash;
}

From source file:Utilities.SendEmailUsingGMailSMTP.java

public void enviarCorreo(String correo, String clave) {
    String to = correo;/*w w w.j a  v  a 2  s.  com*/

    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:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaVerificacionEmailImp.java

@Override
public void enviarAlerta(List<AlertaVerificacion> alertas) {
    try {/*w  w  w.j  a  v a 2 s  .  co  m*/
        for (AlertaVerificacion x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta de Verificacin");
            ST contenido = new ST(contenidoRaw);
            contenido.add("placas", x.getPlacas());
            contenido.add("periodo", x.getPeriodo());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java

private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray)
        throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients",
            FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);

    final Sender sender = Bennu.getInstance().getSystemSender();

    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualizao");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    Multipart multipart = new MimeMultipart();

    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);//from  w  ww.j  a va2 s.  co m

    Transport.send(message);
}

From source file:com.meg7.emailer.EmailerManager.java

private Message createMessage(List<String> emails, String fromEmail, String fromName, String subject,
        String text, Session session) throws MessagingException, UnsupportedEncodingException {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(fromEmail, fromName));
    for (String email : emails) {
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email, email));
    }/*from w ww . java 2  s .co m*/
    message.setSubject(subject);
    message.setText(text);
    return message;
}

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

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

    if (enabled) {

        try {/*ww w .  j a  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();
        }

    }

}

From source file:org.geoserver.wps.mail.SendMail.java

/**
 * Send an EMail to a specified address.
 * //from ww  w.j  av  a  2 s . c o m
 * @param address the to address
 * @param subject the email address
 * @param body message to send
 * @throws MessagingException the messaging exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void send(String address, String subject, String body) {
    try {
        // Session session = Session.getDefaultInstance(props, null);
        Session session = Session.getDefaultInstance(props,
                (conf.getMailSmtpAuth().equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(conf.getUserName(), conf.getPassword());
                    }
                } : null));

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(conf.getFromAddress(), conf.getFromAddressname()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
        message.setSubject(subject);
        message.setText(body.toString());

        Transport.send(message);

    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * Sends email by setting some of the email properties that are common to Secure Email and XDS/NAV
 * //from ww  w  .j av a  2  s  .c  om
 * @param host
 * @param port
 * @param protocol
 * @param senderEmail
 * @param senderUser
 * @param senderPassword
 * @param subject
 * @param message
 * @param recepientEmail
 * @throws EmailException
 */
public void sendEmail(String host, String port, String senderEmail, String senderUser, String senderPassword,
        String subject, String body, String recepientEmail) throws MessagingException {
    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - start");

    final String username = senderUser;
    final String password = senderPassword;

    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", port);

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

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(senderEmail));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recepientEmail));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("Done");

    // Email email = new SimpleEmail();
    // email.setHostName(host);
    // email.setSmtpPort(port);
    // // email.setAuthentication(senderUser, senderPassword);
    // email.setAuthenticator(new DefaultAuthenticator(senderUser, senderPassword));
    // email.addTo(recepientEmail);
    // email.setFrom(senderEmail);
    // email.setSubject(subject);
    // email.setMsg(message);
    // //email.setSSL(true);
    // log.info(String.format("Sending Email to %s, to report successful setup.", recepientEmail));
    // email.send();

    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - end");
}