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:mitm.application.djigzo.james.mailets.StripUnsupportedFormats.java

@Override
public void serviceMail(Mail mail) {
    try {/*from   w w  w .  jav a  2 s .c o  m*/
        MimeMessage filtered = unsupportedFormatStripper.strip(mail.getMessage());

        if (filtered != null) {
            filtered.saveChanges();

            /*
             * A new MimeMessage instance will be created. This makes ure that the 
             * MimeMessage can be written by James (using writeTo()).
             */
            mail.setMessage(new MimeMessage(filtered));
        }
    } catch (MessagingException e) {
        logger.error("Error stripping unsupported formats.", e);
    }
}

From source file:mx.uatx.tesis.managebeans.IndexMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {/*w w  w  .  j ava  2s.  c o  m*/
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:davmail.smtp.TestSmtp.java

public void testSendMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test message\r\n" + "Special characters: \r\n" + "Chinese: " + ((char) 0x604F)
            + ((char) 0x7D59);
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body, "UTF-8");
    sendAndCheckMessage(mimeMessage);//w w w .  j a v a 2 s  .  c  o m
}

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.
 * //from ww w.  ja  va 2s  .co m
 * @param fromAddress
 * @param recipients
 *            - fully qualified recipient address
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient,
        final String[] toRecipients, final String subject, final String body, final String messageType) {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipients == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients");
    }
    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) StringUtils.join(toRecipients);
        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[] toAddresses = new Address[toRecipients.length];
        for (int i = 0; i < toAddresses.length; i++) {
            toAddresses[i] = new InternetAddress(toRecipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddresses);

        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:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*from  ww  w  .  j a v a2  s . c  o  m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

/**
 * Build a {@link MimeMessage} instance from the set of supplied parameters.
 * @return The {@link MimeMessage} instance;
 * @throws MessagingException//from  w  w  w.  j a  va 2 s.  c  o m
 * @throws UnsupportedEncodingException
 */
public MimeMessage buildMimeMessage() throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());

    setJenkinsInstanceIdent(msg);

    msg.setContent("", contentType());
    if (StringUtils.isNotBlank(from)) {
        msg.setFrom(toNormalizedAddress(from));
    }
    msg.setSentDate(new Date());

    addSubject(msg);
    addBody(msg);
    addRecipients(msg);

    if (!replyTo.isEmpty()) {
        msg.setReplyTo(toAddressArray(replyTo));
    }
    return msg;
}

From source file:mitm.common.mail.MailUtils.java

/**
 * Creates a new MimeMessage which is a duplicate of the source message.
 *///from  w  ww .j a  v  a2s.c  om
public static MimeMessage cloneMessage(MimeMessage sourceMessage) throws MessagingException {
    return new MimeMessage(sourceMessage);
}

From source file:populate.java

/**
 * Copy message from src to dst.  If dontPreserveFlags is set
 * we first copy the messages to memory, clear all the flags,
 * and then copy to the destination./*w w  w.j  a  va 2  s.com*/
 */
private static void copyMessages(Folder src, Folder dst) throws MessagingException {
    Message[] msgs = src.getMessages();
    if (dontPreserveFlags) {
        for (int i = 0; i < msgs.length; i++) {
            MimeMessage m = new MimeMessage((MimeMessage) msgs[i]);
            m.setFlags(m.getFlags(), false);
            msgs[i] = m;
        }
    }
    if (warn) {
        // have to copy messages one at a time
        for (int i = 0; i < msgs.length; i++) {
            try {
                src.copyMessages(new Message[] { msgs[i] }, dst);
            } catch (MessagingException mex) {
                System.out.println("WARNING: Copy of message " + (i + 1) + " from " + src.getFullName() + " to "
                        + dst.getFullName() + " failed: " + mex.toString());
            }
        }
    } else
        src.copyMessages(msgs, dst);
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Sends the user a link to reset the password.
 * // ww  w.  jav  a  2 s.  co m
 * @param user
 *            the user
 * @param serverString
 *            host and port of the server
 * @throws CannotSendMailException
 *             if the password reset mail could not be sent
 */
public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Planningsuite password recovery");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("You have requested help recovering the password for the Plato user ");
        builder.append(user.getUsername()).append(".\n\n");
        builder.append("Please use the following link to reset your Planningsuite password: \n");
        builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Sent password reset mail to " + user.getEmail());

    } catch (Exception e) {
        log.error("Error at sending password reset mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail());
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java

@Test
public void testCurruptMessage() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SMIMEEncrypt mailet = new SMIMEEncrypt();

    mailet.init(mailetConfig);/* w  w  w. j  a v a  2 s .  co  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("test@example.com"));

    mail.setRecipients(recipients);

    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    mailAttributes.setCertificates(certificates);

    mailet.service(mail);

    assertEquals(message, mail.getMessage());

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}