Example usage for javax.mail Message setContent

List of usage examples for javax.mail Message setContent

Introduction

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

Prototype

public void setContent(Object obj, String type) throws MessagingException;

Source Link

Document

A convenience method for setting this part's content.

Usage

From source file:org.jkcsoft.java.mail.Emailer.java

/**
 * The final funnel point method that actually uses Java Mail (javax.mail.*)
 * API to send the message.// w  w w .j a  va 2  s .com
 *
 * @throws MessagingException
 */
private void _sendMsg(InternetAddress[] to, InternetAddress[] bccList, InternetAddress from, String subject,
        String msgBody, String strMimeType) throws MessagingException {
    if (Strings.isEmpty(msgBody)) {
        msgBody = "(no email body; see subject)";
    }
    Session session = Session.getDefaultInstance(javaMailProps, null);
    Message msg = new MimeMessage(session);
    msg.setRecipients(Message.RecipientType.TO, to);
    if (bccList != null) {
        msg.setRecipients(Message.RecipientType.BCC, bccList);
    }
    msg.setFrom(from);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setContent(msgBody, strMimeType);
    boolean doTrySend = true;
    int numTries = 0;
    while (doTrySend) {
        numTries++;
        try {
            Transport.send(msg);
            log.info("Sent email; subject=" + subject + " to " + to[0].getAddress() + " ");
            doTrySend = false;
        } catch (MessagingException me) {
            log.warn("Try " + numTries + " of " + MAXTRIES + " failed:", me);
            if (numTries == MAXTRIES) {
                log.error("Failed to send email", me);
                throw me;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                LogHelper.error(this, "Retry sleep interrupted", e1);
            }
            doTrySend = numTries < MAXTRIES;
        }
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void sendBySmtp(String subject, String text, String fromUser, String fromName, final String toUser,
        String telephone, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map<String, Object> model = new HashMap<>();
    model.put("subject", subject);
    model.put("message", text);
    model.put("name", fromName);
    model.put("email", fromUser);
    model.put("telephone", telephone);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/contactus.vm", "UTF-8",
            model);//w w w.  j  ava 2s .  c  o  m
    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        //            message.setText(text);
        message.setContent(body, "text/html;charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:fr.xebia.cocktail.MailService.java

public void sendCocktail(Cocktail cocktail, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);/*from   w  w  w  . j a  v  a2  s. c om*/
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[Cocktail] " + cocktail.getName());
    String message = cocktail.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(cocktail.getInstructions()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    Transport.send(msg);
    auditLogger.info("Sent to {} cocktail '{}'", recipient, cocktail.getName());
    sentEmailCounter.incrementAndGet();
}

From source file:SendMailImpl.java

public void sendMessage(String from, String[] recipients, String subject, String message)
        throws MessagingException {
    boolean debug = false;

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);/*  w w  w . j a  v  a2 s. c o m*/

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

    // set the from and to address
    InternetAddress 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.setContent(message, "text/html");
    Transport.send(msg);
}

From source file:com.cloudbees.demo.beesshop.service.MailService.java

public void sendProductEmail(Product product, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);/*from  ww  w.  j  a  v a  2s  .c o m*/
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[BeesShop] Check this product: " + product.getName());
    String message = product.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(product.getDescription()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    mailSession.getTransport().send(msg);
    auditLogger.info("Sent to {} product '{}'", recipient, product.getName());
    sentEmailCounter.incrementAndGet();
}

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/*www  .  j  a v  a 2s. 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: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//  w  w  w  .  j  av  a  2  s  .  co  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:Implement.DAO.CommonDAOImpl.java

@Override
public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }// w  w  w  .  j a  v a 2  s .co m
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(messageContent, "text/html; charset=utf-8");
    Transport.send(message);
    return true;

}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * //from  w ww  . j a  va2  s .co  m
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

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
 *//*from   w ww.j  a v  a  2 s . com*/
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 + ".");
    }

}