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:com.liferay.mail.imap.IMAPAccessor.java

protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc,
        String subject, String body, List<MailFile> mailFiles)
        throws MessagingException, UnsupportedEncodingException {

    Message jxMessage = new MimeMessage(_imapConnection.getSession());

    jxMessage.setFrom(new InternetAddress(sender, personalName));
    jxMessage.addRecipients(Message.RecipientType.TO, to);
    jxMessage.addRecipients(Message.RecipientType.CC, cc);
    jxMessage.addRecipients(Message.RecipientType.BCC, bcc);
    jxMessage.setSentDate(new Date());
    jxMessage.setSubject(subject);// ww  w. j a  v a  2s.c o  m

    MimeMultipart multipart = new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8);

    multipart.addBodyPart(messageBodyPart);

    if (mailFiles != null) {
        for (MailFile mailFile : mailFiles) {
            File file = mailFile.getFile();

            if (!file.exists()) {
                continue;
            }

            DataSource dataSource = new FileDataSource(file);

            BodyPart attachmentBodyPart = new MimeBodyPart();

            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(mailFile.getFileName());

            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    jxMessage.setContent(multipart);

    return jxMessage;
}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testPerformance() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    int messageSize = 50 * SizeUtils.MB;

    byte[] content = new byte[messageSize];

    Arrays.fill(content, (byte) 'A');

    message.setContent(content, "application/octet-stream");
    message.saveChanges();//from w  w w. j  av  a 2 s  .  c om
    MailUtils.validateMessage(message);

    long start = System.currentTimeMillis();

    int nrOfItems = 10;

    for (int i = 0; i < nrOfItems; i++) {
        proxy.addItem(DEFAULT_REPOSITORY, message,
                InternetAddress.parse("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }

    double msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / add:" + msec);

    assertTrue("Can fail on slower systems", msec < 10000);

    start = System.currentTimeMillis();

    List<? extends MailRepositoryItem> items = proxy.getItems(DEFAULT_REPOSITORY, 0, Integer.MAX_VALUE);

    for (MailRepositoryItem item : items) {
        System.out.println(item.getID());
    }

    msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / get:" + msec);

    assertTrue("Can fail on slower systems", msec < 100);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }//from w  w w. j  a  v  a 2 s  .co  m

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

private Result sendMail(MCPackageMail mcPackageMail) {
    try {//from  ww w. java2  s.  c o m
        Map<String, String> statusAction = new HashMap<>();
        statusAction.put("NEW", "released");
        statusAction.put("CANCEL", "withdrawn");
        statusAction.put("UPDATE", "updated");

        String html = mcPackageMail.getMail();

        ArrayList<String> to = new ArrayList<>();
        to.add(mcPackageMail.getDestination());

        String from = mcPackageMail.getSource();
        String host = Configuration.getInstance().getSmtpHost();
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.localhost", host);
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        for (String s : to) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
        }

        System.out.println("Destination: " + Arrays.asList(to).toString());

        message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", ""));
        message.setContent(html, "text/html");
        Transport.send(message);
        System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-"
                + mcPackageMail.getPackageVersion() + " was succesfully sent!");

    } catch (Exception ex) {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        result.setResultCode("1");
        result.setResultMessage(ex.getMessage());
    }

    return result;
}

From source file:com.intranet.intr.proveedores.EmpControllerGestion.java

public void enviarProvUC(proveedores proveedor) {
    String cuerpo = "";
    String servidorSMTP = "smtp.1and1.es";
    String puertoEnvio = "465";
    Properties props = new Properties();//propiedades a agragar
    props.put("mail.smtp.user", miCorreo);//correo origen
    props.put("mail.smtp.host", servidorSMTP);//tipo de servidor
    props.put("mail.smtp.port", puertoEnvio);//puesto de salida
    props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor
    props.put("mail.smtp.auth", "true");//autentificacion
    props.put("mail.smtp.password", "angel2010");//autentificacion
    props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SecurityManager security = System.getSecurityManager();

    Authenticator auth = new autentificadorSMTP();//autentificar el correo
    Session session = Session.getInstance(props, auth);//se inica una session
    // session.setDebug(true);

    try {//from ww w  . j a  va2  s  .  com
        // Creamos un objeto mensaje tipo MimeMessage por defecto.
        MimeMessage mensajeE = new MimeMessage(session);

        // Asignamos el de o from? al header del correo.
        mensajeE.setFrom(new InternetAddress(miCorreo));

        // Asignamos el para o to? al header del correo.
        mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail()));

        // Asignamos el asunto
        mensajeE.setSubject("Su Perfil Personal");

        // Creamos un cuerpo del correo con ayuda de la clase BodyPart
        //BodyPart cuerpoMensaje = new MimeBodyPart();

        // Asignamos el texto del correo
        String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: "
                + proveedor.getContrasenna()
                + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm";
        // Asignamos el texto del correo
        cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>";
        mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>", "text/html");
        //mensaje.setText(text);

        // Creamos un multipart al correo

        // Enviamos el correo
        Transport.send(mensajeE);
        System.out.println("Mensaje enviado");

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

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/*from   www.jav a 2  s .  co m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();//w  w  w.j  ava  2  s .com
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Common part for sending message process :
 * <ul>//w  w  w.j  a v a  2s .  c o  m
 * <li>initializes a mail session with the SMTP server</li>
 * <li>activates debugging</li>
 * <li>instantiates and initializes a mime message</li>
 * <li>sets the sent date, the from field, the subject field</li>
 * <li>sets the recipients</li>
 * </ul>
 *
 *
 * @return the message object initialized with the common settings
 * @param strRecipientsTo The list of the main recipients email.Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param session The SMTP session object
 * @throws AddressException If invalid address
 * @throws MessagingException If a messaging error occurred
 */
protected static Message prepareMessage(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc,
        String strSenderName, String strSenderEmail, String strSubject, Session session)
        throws MessagingException, AddressException {
    // Instantiate and initialize a mime message
    Message msg = new MimeMessage(session);
    msg.setSentDate(new Date());

    try {
        msg.setFrom(new InternetAddress(strSenderEmail, strSenderName,
                AppPropertiesService.getProperty(PROPERTY_CHARSET)));
        msg.setSubject(MimeUtility.encodeText(strSubject, AppPropertiesService.getProperty(PROPERTY_CHARSET),
                ENCODING));
    } catch (UnsupportedEncodingException e) {
        throw new AppException(e.toString());
    }

    // Instantiation of the list of address
    if (strRecipientsTo != null) {
        msg.setRecipients(Message.RecipientType.TO, getAllAdressOfRecipients(strRecipientsTo));
    }

    if (strRecipientsCc != null) {
        msg.setRecipients(Message.RecipientType.CC, getAllAdressOfRecipients(strRecipientsCc));
    }

    if (strRecipientsBcc != null) {
        msg.setRecipients(Message.RecipientType.BCC, getAllAdressOfRecipients(strRecipientsBcc));
    }

    return msg;
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress)
        throws MessagingException {

    MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart();

    // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview)
    MimeMultipart cover = new MimeMultipart("alternative");
    htmlAndPlainTextAlternativeBody.setContent(cover);
    BodyPart textHtmlBodyPart = new MimeBodyPart();
    String textHtmlBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".html.ftl");
    textHtmlBodyPart.setContent(textHtmlBody, "text/html");
    cover.addBodyPart(textHtmlBodyPart);

    BodyPart textPlainBodyPart = new MimeBodyPart();
    cover.addBodyPart(textPlainBodyPart);
    String textPlainBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".txt.ftl");
    textPlainBodyPart.setContent(textPlainBody, "text/plain");

    MimeMultipart content = new MimeMultipart("related");
    content.addBodyPart(htmlAndPlainTextAlternativeBody);

    // ATTACHMENTS
    for (BodyPart bodyPart : attachments) {
        content.addBodyPart(bodyPart);// w w w  .j  av  a2  s  .c  o m
    }

    MimeMessage msg = new MimeMessage(mailSession);

    msg.setFrom(mailFrom);
    msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
    msg.addRecipient(javax.mail.Message.RecipientType.CC, mailFrom);

    String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials";

    msg.setSubject(subject);
    msg.setContent(content);

    mailTransport.sendMessage(msg, msg.getAllRecipients());
}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

public void sendErrorEmail(Throwable t, String xml, String url) {
    try {//from  w  w w .  j ava2s. c  o  m
        Properties props = new Properties();
        props.put("mail.smtp.host", "server.kite9.org");
        Session session = Session.getInstance(props);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("servicetest@kite9.com"));
        msg.setRecipient(RecipientType.TO, new InternetAddress("rob@kite9.com"));
        String name = ctx.getServletContextName();
        boolean local = isLocal();
        msg.setSubject("Failure in " + (local ? "TEST" : name) + " Service: " + this.getClass().getName());
        StringWriter sw = new StringWriter(10000);
        PrintWriter pw = new PrintWriter(sw);
        pw.write("URL: " + url + "\n");

        t.printStackTrace(pw);

        if (xml != null) {
            pw.println();
            pw.print(xml);
        }

        pw.close();
        msg.setText(sw.toString());
        Transport.send(msg);
    } catch (Exception e) {
    } finally {
        t.printStackTrace();
    }
}