Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage MimeMessage.

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.utils.MailUtil.java

public void sendMessage(String messageText, String subject, String from, String to, List<String> deliverToArray)
        throws IOException {

    Session s = FreemarkerEmailFactory.getEmailSession(req);

    try {/*from w  ww  .  jav  a 2s.c  o  m*/

        int recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();
        if (recipientCount == 0) {
            log.error("To establish the Contact Us mail capability the system administrators must  "
                    + "specify at least one email address in the current portal.");
        }

        MimeMessage msg = new MimeMessage(s);
        // Set the from address
        msg.setFrom(new InternetAddress(from));

        // Set the recipient address

        if (recipientCount > 0) {
            InternetAddress[] address = new InternetAddress[recipientCount];
            for (int i = 0; i < recipientCount; i++) {
                address[i] = new InternetAddress(deliverToArray.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        // Set the subject and text
        msg.setSubject(subject);

        // add the multipart to the message
        msg.setContent(messageText, "text/html");

        // set the Date: header
        msg.setSentDate(new Date());
        Transport.send(msg); // try to send the message via smtp - catch error exceptions
    } catch (Exception ex) {
        log.error("Exception sending message :" + ex.getMessage(), ex);
    }
}

From source file:com.sun.socialsite.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.// ww w.ja  v  a2 s .co  m
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Startup.getMailProvider().getTransport().sendMessage(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from   w  w w.  ja v  a  2 s  .c  om
 *
 * @param from     e-mail address of sender
 * @param to       e-mail address(es) of recipients
 * @param subject  subject of e-mail
 * @param content  the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled()) {
            mLogger.debug("e-mail from: " + sentFrom);
        }
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("sending e-mail to: " + to[i]);
            }
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("copying e-mail to: " + cc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome) {
        throw sendex;
    }
}

From source file:org.jrecruiter.mock.MockJavaMailSender.java

@Override
public void send(MimeMessagePreparator preparator) throws MailException {

    message = new MimeMessage((Session) null);
    try {/*from w ww.  j  ava 2s .  c o  m*/
        preparator.prepare(message);
    } catch (Exception e) {
        throw new IllegalStateException("Error while preparing message.", e);
    }

    LOGGER.info("send() - Mock message successfully sent.");

}

From source file:gmailclientfx.models.FetchMessageCallable.java

public MyMessage fetchMessage(MimeMessage m, int tblIndex, String lbl) throws MessagingException, Exception {
    MimeMessage msg = new MimeMessage(m);
    MimeMessageParser parser = new MimeMessageParser(msg);
    parser.parse();/*from  www .ja va  2 s.co m*/

    String naslov = parser.getSubject();
    String from = parser.getFrom();
    Address[] to = msg.getRecipients(Message.RecipientType.TO);
    String toStr = "";
    if (to.length > 1) {
        for (int k = 0; k < to.length; k++) {
            if (k == to.length - 1)
                toStr += to[k].toString();
            else
                toStr += to[k].toString() + ",";
        }
    } else {
        toStr = to[0].toString();
    }
    String body = parser.getHtmlContent();
    if (body.equals(""))
        body = parser.getPlainContent();
    String date = msg.getSentDate().toString();
    String label = lbl;

    MyMessage myMsg = new MyMessage(User.getUserId(GmailClient.getEmail()), naslov, from, toStr, body, date,
            label);
    myMsg.setTblId(tblIndex);
    return myMsg;
}

From source file:gov.nih.nci.caintegrator.application.mail.SendMail.java

public synchronized void sendMail(String mailTo, String mailCC, String mailBody, String subject)
        throws ValidationException {
    try {/*from   w  w  w  .  ja v a2s.  co m*/
        if (mailTo != null && EmailValidator.getInstance().isValid(mailTo)) {
            //get system properties
            Properties props = System.getProperties();

            String to = mailTo;
            // Set up mail server

            props.put("mail.smtp.host", MailConfig.getInstance(mailProperties).getHost());

            //Get session
            Session session = Session.getDefaultInstance(props, null);

            //Define Message
            MimeMessage message = new MimeMessage(session);
            MailManager mailManager = new MailManager(mailProperties);
            message.setFrom(new InternetAddress(mailManager.formatFromAddress()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if ((mailCC != null) && EmailValidator.getInstance().isValid(mailCC))
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCC));
            message.setSubject(subject);
            message.setText(mailBody);

            //Send Message

            Transport.send(message);
        } else {
            throw new ValidationException("Invalid Email Address");
        }
    } catch (Exception e) {
        logger.error("Send Mail error", e);
    } //catch
}

From source file:easyproject.service.Mail.java

public void sendMail() {
    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

    Session session = Session.getInstance(props, null);

    try {//from   www.  j  av a 2  s. co  m
        MimeMessage message = new MimeMessage(session);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message.setSubject(asunto);
        message.setSentDate(new Date());
        message.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

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 av a 2s  .  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:cl.preguntame.controller.PlataformaController.java

@ResponseBody
@RequestMapping(value = "/email", method = RequestMethod.POST)
public String correo(HttpServletRequest req) {

    try {//from w w  w  .  j  a va2s.c  om
        String host = "smtp.gmail.com";

        Properties prop = System.getProperties();

        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", "hector.riquelme1169@gmail.com");
        prop.put("mail.smtp.password", "rriiqquueellmmee");
        prop.put("mail.smtp.port", 587);
        prop.put("mail.smtp.auth", "true");

        Session sesion = Session.getDefaultInstance(prop, null);
        MimeMessage mensaje = new MimeMessage(sesion);

        mensaje.setFrom(new InternetAddress());
        mensaje.setRecipient(Message.RecipientType.TO, new InternetAddress("hector.riquelme1169@gmail.com"));
        mensaje.setSubject("CONTACTO MIS CONCEPTOS");
        mensaje.setText(req.getParameter("mensaje_contacto"));

        Transport transport = sesion.getTransport("smtp");
        transport.connect(host, "hector.riquelme1169@gmail.com", "rriiqquueellmmee");
        transport.sendMessage(mensaje, mensaje.getAllRecipients());

        transport.close();

    } catch (Exception e) {

    }

    return req.getParameter("mensaje_contacto") + "  -  " + req.getParameter("email_contacto");
}

From source file:org.openlmis.notification.service.NotificationServiceTest.java

@Test
public void shouldSendMessage() throws MessagingException {
    MimeMessage mimeMessage = new MimeMessage(session);
    when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
    service.sendNotification("from@example.com", "to@example.com", "subject", "content");
    verify(javaMailSender).send(mimeMessage);
}