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:com.waveerp.sendMail.java

public void sendMsgSSL(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.socketFactory.port", strPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/*from ww w  .  j a  va2  s  .  c om*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

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

    //log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass );

}

From source file:org.blue.star.plugins.send_mail.java

public boolean execute_check() {

    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    if (smtpAuth) {
        props.put("mail.smtp.auth", "true");
    }/*from  ww  w.  j  a  v  a2s  .c  o m*/

    Session session = Session.getInstance(props, null);
    SMTPTransport transport = null;
    //      if (debug)
    //         session.setDebug(true);

    // construct the message
    try {
        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 (subject != null)
            msg.setSubject(subject);

        msg.setHeader("X-Mailer", "blue-send-mail");
        msg.setSentDate(new Date());
        msg.setText(message.replace("\\n", "\n").replace("\\t", "\t"));

        transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        if (smtpAuth)
            transport.connect(smtpServer, smtpUser, smtpPass);
        else
            transport.connect();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

    } catch (MessagingException mE) {
        mE.printStackTrace();
        this.state = common_h.STATE_CRITICAL;
        this.text = mE.getMessage();
        return false;
    } finally {
        try {
            transport.close();
        } catch (Exception e) {
        }
    }

    state = common_h.STATE_OK;
    text = "Message Sent!";
    return true;
}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//from   w ww .  jav a 2  s.c  o  m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

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

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

/**
 * Convenience method for creating an e-mail message from a set of message properties.
 *
 * @param session the mail Session instance to use
 * @param config the email configuration to use
 * @param recipientAddress the e-mail address of the recipient
 * @param subject the e-mail subject line
 * @param message the e-mail message body
 *
 * @return a Message instance/*from  w w w  .j a  v  a  2 s  . c  om*/
 *
 * @since hobson-hub-api 0.1.6
 */
protected Message createMessage(Session session, EmailConfiguration config, String recipientAddress,
        String subject, String message) {
    if (config.getSenderAddress() == null) {
        throw new HobsonInvalidRequestException("No sender address specified; unable to execute e-mail action");
    } else if (recipientAddress == null) {
        throw new HobsonInvalidRequestException(
                "No recipient address specified; unable to execute e-mail action");
    } else if (subject == null) {
        throw new HobsonInvalidRequestException("No subject specified; unable to execute e-mail action");
    } else if (message == null) {
        throw new HobsonInvalidRequestException("No message body specified; unable to execute e-mail action");
    }

    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(config.getSenderAddress()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
        msg.setSubject(subject);
        msg.setText(message);

        return msg;
    } catch (MessagingException e) {
        throw new HobsonInvalidRequestException("Unable to create mail message", 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 {/*  w w  w. j a v  a2  s. com*/
        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.fao.geonet.services.register.SelfRegister.java

/**
 * Send an email.//  w  ww .  j a va  2  s . com
 * 
 * @param host
 * @param port
 * @param subject
 * @param from
 * @param to
 * @param content
 * @return
 */
boolean sendMail(String host, int port, String subject, String from, String to, String content) {
    boolean isSendout = false;

    Properties props = new Properties();

    props.put("mail.transport.protocol", PROTOCOL);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.auth", "false");

    Session mailSession = Session.getDefaultInstance(props);

    try {
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSentDate(new Date());
        msg.setSubject(subject);
        // Add content message
        msg.setText(content);
        Transport.send(msg);
        isSendout = true;
    } catch (AddressException e) {
        isSendout = false;
        e.printStackTrace();
    } catch (MessagingException e) {
        isSendout = false;
        e.printStackTrace();
    }
    return isSendout;
}

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

private void sendMail(LDAPUser user) throws MailException {
    javax.mail.Session session = null;/*ww  w.  j av a2  s.  c o 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, mailFrom));

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

        mailMsg.setSubject(mailSubject);

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

        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:org.apache.jmeter.reporters.MailerModel.java

/**
 * Sends a mail with the given parameters using SMTP.
 *
 * @param from//from  ww w  .  j  ava2 s  .  com
 *            the sender of the mail as shown in the mail-client.
 * @param vEmails
 *            all receivers of the mail. The receivers are seperated by
 *            commas.
 * @param subject
 *            the subject of the mail.
 * @param attText
 *            the message-body.
 * @param smtpHost
 *            the smtp-server used to send the mail.
 * @param smtpPort the smtp-server port used to send the mail.
 * @param user the login used to authenticate
 * @param password the password used to authenticate
 * @param mailAuthType {@link MailAuthType} Security policy
 * @param debug Flag whether debug messages for the mail session should be generated
 * @throws AddressException If mail address is wrong
 * @throws MessagingException If building MimeMessage fails
 */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost,
        String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug)
        throws AddressException, MessagingException {

    InternetAddress[] address = new InternetAddress[vEmails.size()];

    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }

    // create some properties and get the default Session
    Properties props = new Properties();

    props.put(MAIL_SMTP_HOST, smtpHost);
    props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch (mailAuthType) {
        case SSL:
            props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
            break;
        case TLS:
            props.put(MAIL_SMTP_STARTTLS, "true");
            break;

        default:
            break;
        }
    }

    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

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

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}

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

private void sendMail() throws MailException {
    javax.mail.Session session = null;//  w ww. j  av a2s  .  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, mailFrom));

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

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

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

        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:Model.DAO.java

public void sendEmail(int id, String status) {
    SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
    Properties props = new Properties();
    /** Parmetros de conexo com servidor Gmail */
    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("seuemail@gmail.com", "suasenha");
        }//from  ww  w  .j a  va 2  s.  c  o m
    });

    /** Ativa Debug para sesso */

    try {
        PreparedStatement stmt = this.conn
                .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?");
        stmt.setInt(1, id);
        ResultSet rs = stmt.executeQuery();
        rs.next();
        String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0];
        String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1];
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente

        Address[] toUser = InternetAddress //Destinatrio(s)
                .parse(rs.getString("email"));

        message.setRecipients(Message.RecipientType.TO, toUser);
        message.setSubject("Status Reserva");//Assunto
        message.setText("Email de alterao do status da resreva no dia " + date + " s " + time
                + " horas para " + status);
        /**Mtodo para enviar a mensagem criada*/
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (SQLException ex) {
        Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}