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: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 w  w.  j  a  va 2 s  .c om*/
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:org.eclipse.skalli.core.mail.MailComponent.java

private void sendMailInternal(Address[] rcptTo, Address[] rcptCC, Address[] rcptBCC, Address from,
        String subject, String body) {
    try {//from   w  w w.j  a v a 2 s.  c  o m
        String mailHost = "mail.sap.corp"; //$NON-NLS-1$
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailHost); //$NON-NLS-1$
        Session session = Session.getInstance(props, null);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        if (rcptTo != null && rcptTo.length > 0) {
            message.setRecipients(Message.RecipientType.TO, rcptTo);
        }
        if (rcptCC != null && rcptCC.length > 0) {
            message.setRecipients(Message.RecipientType.CC, rcptCC);
        }
        if (rcptBCC != null && rcptBCC.length > 0) {
            message.setRecipients(Message.RecipientType.BCC, rcptBCC);
        }

        message.setSubject(subject);
        message.setContent(body, "text/plain"); //$NON-NLS-1$
        Transport.send(message);
    } catch (AddressException e) {
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bia.monitor.service.EmailService.java

/**
 *
 * @param addressTo// ww  w .ja  v a 2  s . c  o m
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    logger.info("sending email.. " + addressTo);
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    InternetAddress[] bcc1 = getBCC();
    msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:com.bia.gmailjava.EmailService.java

/**
 *
 * @param addressTo/*from   w  w w  .j  a  v a2 s.c  om*/
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    //InternetAddress[] bcc1 = getBCC();
    //msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java

public void enviarEmailHtml(List<String> destinos, String msg, String titulo) {
    //       Recipient's email ID needs to be mentioned.
    String to = "";
    String rodape = "<br/><br/><br/><br/>  <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">"
            + "Esta mensagem  uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> "
            + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>"
            + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>"
            + "</div>";
    for (String d : destinos) {
        if (d.equals(destinos.get(destinos.size() - 1))) {
            to = to.concat(d);//from www.j  av a2 s.  com
        } else {
            to = to.concat(d.concat(","));
        }
    }

    // Sender's email ID needs to be mentioned
    String from = this.email;
    final String username = this.email;//change accordingly
    final String password = this.senha;//change accordingly

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

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        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(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject(titulo);

        // Send the actual HTML message, as big as you like
        message.setContent(msg + rodape, "text/html");

        // Send message
        Transport.send(message);

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

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

@Override
public void send(IMessage message) {
    try {/*from   w w  w . ja  v a 2 s.co  m*/
        Message mail = new MimeMessage(getSession());

        mail.addFrom(new InternetAddress[] { new InternetAddress(message.getSender()) });
        Set<String> recipients = message.getRecipients();
        if (recipients.isEmpty())
            return;
        for (String recipient : recipients) {
            mail.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        mail.setSubject(message.getSubject());
        mail.setContent(message.getBody(), message.getContentType());

        Transport.send(mail);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*  w  ww  .  j a va 2s  .c  o m*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content) {
    Message msg = new MimeMessage(session);
    try {//from   www . j a  va  2  s  .c o  m
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(title);
        if (to != null) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));
        msg.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(msg);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

@Override
protected void sendInternal(Map.Entry<String, String> from, Map.Entry<String, String> replyTo,
        Map<String, String> to, Map<String, String> cc, Map<String, String> bcc, String subject, Object body,
        List<Attachment> attachments) {
    try {/*from   w w  w  . j  ava2 s .c  o  m*/
        Session emailSession = getSession();

        Message message = new MimeMessage(emailSession);
        message.setFrom(emailAddress(from));
        if (replyTo != null) {
            message.setReplyTo(new Address[] { emailAddress(replyTo) });
        }

        message.setSubject(subject);

        BasicViewRenderer viewRenderer = render(body);
        String content = viewRenderer.getOutputAsString();
        String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
        contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

        if (Expressive.isEmpty(attachments)) {
            message.setContent(content, contentType);
        } else {
            Multipart multipart = new MimeMultipart("mixed"); // subtype must be "mixed" or inline & regular attachments won't play well together
            addBody(multipart, content, contentType);
            addAttachments(multipart, attachments);
            message.setContent(multipart);
        }

        addRecipients(to, message, RecipientType.TO);
        addRecipients(cc, message, RecipientType.CC);
        addRecipients(bcc, message, RecipientType.BCC);

        sendMessage(message);
    } catch (MessagingException e) {
        throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
}

From source file:net.kamhon.ieagle.function.email.SendMail.java

public void send(String to, String cc, String bcc, String from, String subject, String text, String emailType) {

    // Session session = Session.getInstance(props, null);
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailServerSetting.getUsername(),
                    emailServerSetting.getPassword());
        }// w ww.  ja  v a 2 s.c o  m
    });

    session.setDebug(emailServerSetting.isDebug());

    try {
        Message msg = new MimeMessage(session);
        if (StringUtils.isNotBlank(from)) {
            msg.setFrom(new InternetAddress(from));
        } else {
            msg.setFrom();
        }

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (StringUtils.isNotBlank(cc)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if (StringUtils.isNotBlank(bcc)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        msg.setSubject(subject);
        if (Emailq.TYPE_HTML.equalsIgnoreCase(emailType)) {
            msg.setContent(text, "text/html");
        } else {
            msg.setText(text);
        }
        msg.setSentDate(new java.util.Date());
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        throw new SystemErrorException(mex);
    }
}