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.sonicle.webtop.mail.Service.java

private SimpleMessage getForwardMsg(long id, Message msg, boolean richContent, String fromtitle, String totitle,
        String cctitle, String datetitle, String subjecttitle, boolean attached) {
    Message forward = new MimeMessage(mainAccount.getMailSession());
    if (!attached) {
        try {/*ww w.  j  ava2s. c  om*/
            StringBuffer htmlsb = new StringBuffer();
            StringBuffer textsb = new StringBuffer();
            boolean isHtml = appendReplyParts(msg, htmlsb, textsb, null);
            //      Service.logger.debug("isHtml="+isHtml);
            //      Service.logger.debug("richContent="+richContent);
            String html = "<HTML><BODY>" + htmlsb.toString() + "</BODY></HTML>";
            if (!richContent) {
                forward.setText(getForwardBody(msg, textsb.toString(), SimpleMessage.FORMAT_TEXT, false,
                        fromtitle, totitle, cctitle, datetitle, subjecttitle));
            } else if (!isHtml) {
                forward.setText(getForwardBody(msg, textsb.toString(), SimpleMessage.FORMAT_PREFORMATTED, false,
                        fromtitle, totitle, cctitle, datetitle, subjecttitle));
            } else {
                forward.setText(MailUtils.removeMSWordShit(getForwardBody(msg, html, SimpleMessage.FORMAT_HTML,
                        true, fromtitle, totitle, cctitle, datetitle, subjecttitle)));
            }
        } catch (Exception exc) {
            Service.logger.error("Exception", exc);
        }
    }

    try {
        String msgid = null;
        String vh[] = msg.getHeader("Message-ID");
        if (vh != null) {
            msgid = vh[0];
        }
        if (msgid != null) {
            forward.setHeader("Forwarded-From", msgid);
        }
    } catch (MessagingException exc) {
        Service.logger.error("Exception", exc);
    }

    SimpleMessage fwd = new SimpleMessage(id, forward);
    fwd.setTo("");

    // Update appropriate subject
    // Fwd: subject
    try {
        String subject = msg.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (!subject.toLowerCase().startsWith("fwd: ")) {
            fwd.setSubject("Fwd: " + subject);
        } else {
            fwd.setSubject(msg.getSubject());
        }
    } catch (MessagingException e) {
        Service.logger.error("Exception", e);
        //      Service.logger.debug("*** SimpleMessage: " +e);
    }

    return fwd;
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();
    boolean doAuth = false;
    props.setProperty("mail.smtp.host", prov.getSmtpHost());
    props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort()));
    if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) {
        logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication");
        props.setProperty("mail.smtp.user", prov.getSmtpUser());
        props.setProperty("mail.smtp.auth", "true");
        doAuth = true;/*from  w  ww  .j  ava2s .  c  o  m*/
    } else {
        logger.debug("No SMTP user, disabling authentication");
        doAuth = false;
        props.setProperty("mail.smtp.auth", "false");
    }
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS()));
    if (logger.isDebugEnabled()) {
        props.setProperty("mail.debug", "true");
        props.setProperty("mail.socket.debug", "true");
    }

    if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", prov.getLocalhost());
    }

    if (prov.isUseSOCKSProxy()) {

        props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort()));
        props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));

    Session session = null;
    if (doAuth) {
        logger.debug("Creating authenticated session");
        session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword());
            }
        });
    } else {
        logger.debug("Creating unauthenticated session");
        session = Session.getInstance(props);
    }
    if (logger.isDebugEnabled()) {
        session.setDebugOut(System.out);
        session.setDebug(true);
    }
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);

    if (msg.contentType != null) {
        msgToSend.setContent(msg.msg, msg.contentType);
    } else {
        msgToSend.setText(msg.msg);
    }

    msgToSend.saveChanges();
    Transport.send(msgToSend);

    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

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

    message.setSubject("test");
    message.setContent("test", "text/plain");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/certificate-base64-encode-bug.cer");

    builder.addRecipient(certificate, SMIMERecipientMode.ISSUER_SERIAL);

    builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC);

    MimeMessage newMessage = builder.buildMessage();

    newMessage.saveChanges();//  w ww  .  j a va 2s .co  m

    File file = new File(tempDir, "testEncryptBase64EncodeBug.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    newMessage.writeTo(new SkipHeadersOutputStream(bos));

    String blob = new String(bos.toByteArray(), "us-ascii");

    // check if all lines are not longer than 76 characters
    LineIterator it = IOUtils.lineIterator(new StringReader(blob));

    while (it.hasNext()) {
        String next = it.nextLine();

        if (next.length() > 76) {
            fail("Line length exceeds 76: " + next);
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent)
        throws MessagingException {
    MimeMessage reply = new MimeMessage(account.getMailSession());
    /*/*  www. j a  v a 2 s . c  o  m*/
     * Have to manipulate the raw Subject header so that we don't lose
     * any encoding information.  This is safe because "Re:" isn't
     * internationalized and (generally) isn't encoded.  If the entire
     * Subject header is encoded, prefixing it with "Re: " still leaves
     * a valid and correct encoded header.
     */
    String subject = orig.getHeader("Subject", null);
    if (subject != null) {
        if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) {
            subject = "Re: " + subject;
        }
        reply.setHeader("Subject", subject);
    }
    Address a[] = null;
    if (!fromSent)
        a = orig.getReplyTo();
    else {
        Address ax[] = orig.getRecipients(RecipientType.TO);
        if (ax != null) {
            a = new Address[1];
            a[0] = ax[0];
        }
    }
    reply.setRecipients(Message.RecipientType.TO, a);
    if (replyToAll) {
        Vector v = new Vector();
        Session session = account.getMailSession();
        // add my own address to list
        InternetAddress me = InternetAddress.getLocalAddress(session);
        if (me != null) {
            v.addElement(me);
        }
        // add any alternate names I'm known by
        String alternates = null;
        if (session != null) {
            alternates = session.getProperty("mail.alternates");
        }
        if (alternates != null) {
            eliminateDuplicates(v, InternetAddress.parse(alternates, false));
        }
        // should we Cc all other original recipients?
        String replyallccStr = null;
        boolean replyallcc = false;
        if (session != null) {
            replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false);
        }
        // add the recipients from the To field so far
        eliminateDuplicates(v, a);
        a = orig.getRecipients(Message.RecipientType.TO);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            if (replyallcc) {
                reply.addRecipients(Message.RecipientType.CC, a);
            } else {
                reply.addRecipients(Message.RecipientType.TO, a);
            }
        }
        a = orig.getRecipients(Message.RecipientType.CC);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            reply.addRecipients(Message.RecipientType.CC, a);
        }
        // don't eliminate duplicate newsgroups
        a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS);
        if (a != null && a.length > 0) {
            reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a);
        }
    }

    String msgId = orig.getHeader("Message-Id", null);
    if (msgId != null) {
        reply.setHeader("In-Reply-To", msgId);
    }

    /*
     * Set the References header as described in RFC 2822:
     *
     * The "References:" field will contain the contents of the parent's
     * "References:" field (if any) followed by the contents of the parent's
     * "Message-ID:" field (if any).  If the parent message does not contain
     * a "References:" field but does have an "In-Reply-To:" field
     * containing a single message identifier, then the "References:" field
     * will contain the contents of the parent's "In-Reply-To:" field
     * followed by the contents of the parent's "Message-ID:" field (if
     * any).  If the parent has none of the "References:", "In-Reply-To:",
     * or "Message-ID:" fields, then the new message will have no
     * "References:" field.
     */
    String refs = orig.getHeader("References", " ");
    if (refs == null) {
        // XXX - should only use if it contains a single message identifier
        refs = orig.getHeader("In-Reply-To", " ");
    }
    if (msgId != null) {
        if (refs != null) {
            refs = MimeUtility.unfold(refs) + " " + msgId;
        } else {
            refs = msgId;
        }
    }
    if (refs != null) {
        reply.setHeader("References", MimeUtility.fold(12, refs));
    }

    //try {
    //    setFlags(answeredFlag, true);
    //} catch (MessagingException mex) {
    //    // ignore it
    //}
    return reply;
}

From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java

@Override
public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) {

    //<editor-fold defaultstate="collapsed" desc="Inicio">
    LOGGER.info("Iniciando el metodo obtenerCotizacionInternet...");
    OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO();
    String codigo;/*from w  w  w . j a  v a  2  s  . co  m*/
    String mensaje;
    XStream xStream = new XStream();
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Validacion de entrada">
    OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input);
    if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) {
        codigo = Integer.toString(outputValidacion.getCodigo());
        mensaje = outputValidacion.getMensaje();
        LOGGER.info(mensaje);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer">
    String numeroCotizacion = input.getNumeroCotizacion();
    InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet();
    inputCotizacionInternet.setIdCotizacion(numeroCotizacion);
    String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet);
    LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet);
    servicioJasperServer = new ServicioJasperServerJerseyImpl();
    ResultadoDocumentoVO outputJasperServer;
    try {
        outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet);
        String xmlOutputJasperServer = xStream.toXML(outputJasperServer);
        LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer);
        String codigoJasperServer = outputJasperServer.getCodigo();
        if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) {
            codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
            mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
            LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
        mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida">
    ClienteServicioCotizadorVida clienteCotizadorVida;
    try {
        clienteCotizadorVida = new ClienteServicioCotizadorVida();
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }

    //Se busca el nombre del asegurado, glosa del plan y numero de propuesta        
    LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet);
    OutputEmailCotizacionInternetVO outputEmail;
    try {
        outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet);
        String xmlOutputEmail = xStream.toXML(outputEmail);
        LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail);
        String codigoOutputEmail = outputEmail.getCodigo();
        if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) {
            codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
            mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
            LOGGER.info(mensaje + ": " + outputEmail.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }

    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto">
    String documento = outputJasperServer.getDocumento();
    try {
        EmailVO datosEmail = outputEmail.getDatosEmail();
        String htmlBody = Propiedades.getFuncProperty("email.html");
        String nombreAsegurable = datosEmail.getNombreAsegurable();
        if (nombreAsegurable == null) {
            nombreAsegurable = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable);
        String glosaPlan = datosEmail.getGlosaPlan();
        if (glosaPlan == null) {
            glosaPlan = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan);
        String numeroPropuesta = datosEmail.getNumeroPropuesta();
        if (numeroPropuesta == null) {
            numeroPropuesta = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta);

        //Parametrizar imagenes
        String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde");
        if (imgBulletBgVerde == null) {
            imgBulletBgVerde = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde);

        String imgFace = Propiedades.getFuncProperty("email.images.face");
        if (imgFace == null) {
            imgFace = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace);

        String imgTwitter = Propiedades.getFuncProperty("email.images.twitter");
        if (imgTwitter == null) {
            imgTwitter = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter);

        String imgYoutube = Propiedades.getFuncProperty("email.images.youtube");
        if (imgYoutube == null) {
            imgYoutube = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube);

        String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115");
        if (imgMail15 == null) {
            imgMail15 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15);

        String imgFono = Propiedades.getFuncProperty("email.images.fono");
        if (imgFono == null) {
            imgFono = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono);

        String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116");
        if (imgMail16 == null) {
            imgMail16 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16);

        byte[] attachmentData = Base64.decodeBase64(documento);

        final String username = Propiedades.getKeyProperty("email.username");
        final String encryptedPassword = Propiedades.getKeyProperty("email.password");
        String privateKeyFile = Propiedades.getConfProperty("KEY");
        CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile);
        final String password = cryptoUtil.decryptData(encryptedPassword);
        final String auth = Propiedades.getFuncProperty("email.auth");
        final String starttls = Propiedades.getFuncProperty("email.starttls");
        final String host = Propiedades.getFuncProperty("email.host");
        final String port = Propiedades.getFuncProperty("email.port");

        //Log de datos de correo
        String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host
                + "\n";
        LOGGER.info("Datos correo: \n".concat(strDatosCorreo));

        Properties props = new Properties();
        props.put("mail.smtp.auth", auth);
        if (!"0".equals(starttls)) {
            props.put("mail.smtp.starttls.enable", starttls);
        }
        props.put("mail.smtp.host", host);
        if (!"0".equals(port)) {
            props.put("mail.smtp.port", port);
        }
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name");
        fileName = fileName.replaceAll("%s", numeroPropuesta);
        fileName = fileName + ".pdf";

        // creates a new e-mail message
        Message msg = new MimeMessage(session);
        String from = Propiedades.getFuncProperty("email.from");
        msg.setFrom(new InternetAddress(from));
        //TODO considerar email de prueba o email del asegurado            
        String emailTo;
        if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) {
            emailTo = Propiedades.getFuncProperty("email.to.mail");
        } else {
            emailTo = datosEmail.getEmail();
        }
        InternetAddress[] toAddresses = { new InternetAddress(emailTo) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        String subject = Propiedades.getFuncProperty("email.subject");
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        // creates message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(htmlBody, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // adds attachments
        MimeBodyPart attachPart = new MimeBodyPart();
        DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf");
        attachPart.setDataHandler(new DataHandler(dataSource));
        attachPart.setFileName(fileName);
        multipart.addBodyPart(attachPart);

        // sets the multi-part as e-mail's content
        msg.setContent(multipart);

        // sends the e-mail
        Transport.send(msg);

    } catch (Exception ex) {
        codigo = Propiedades.getFuncProperty("email.error.codigo");
        mensaje = Propiedades.getFuncProperty("email.error.mensaje");
        LOGGER.error(mensaje + ": " + ex.getMessage(), ex);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Termino">
    codigo = Propiedades.getFuncProperty("codigo.ok");
    mensaje = Propiedades.getFuncProperty("mensaje.ok");
    output.setCodigo(codigo);
    output.setMensaje(mensaje);
    return output;
    //</editor-fold>

}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl)
        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", "smtpm.csloxinfo.com");

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

    //Create data for referral
    java.util.Date date = new java.util.Date();
    String s = providerID + (new Timestamp(date.getTime()).toString());
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    m.update(s.getBytes(), 0, s.length());
    String md5 = (new BigInteger(1, m.digest()).toString(16));

    String title = "You have an invitation from your friend.";
    String receiver = request.getParameter("email");

    //        StringBuilder messageContentHtml = new StringBuilder();
    //        messageContentHtml.append(request.getParameter("message") + "<br />\n");
    //        messageContentHtml.append("You can become a provider from here:  " + baseUrl + "/Common/Provider/SignupReferral/" + md5);
    //        String messageContent = messageContentHtml.toString();
    String emailContent = "  <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>"
            + "            <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>"
            + providerName + "</b> has invited you to complete purchase via</p>"
            + "            <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5
            + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;"
            + "                    background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>"
            + "            <p style='font-size:16px;margin:30px;'><b>" + providerName
            + "</b> will get 25 credit</p>"
            + "            <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>"
            + "            <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>"
            + "            " + "            " + "        </div>";

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(emailContent, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    mp.addBodyPart(backgroundImage);
    mp.addBodyPart(giftImage);
    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(mp);
    message.saveChanges();
    Transport.send(message);

    ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()),
            md5, 0);
    referralDAO.insertNewReferral(referral);
    return true;
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendEmailReferral(String data, int providerID, String baseUrl) 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);
        }/*from ww w .  j  a  va2s.co m*/
    });

    String title = "You have an invitation from your friend.";

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    String content = jsonObject.get("content").getAsString();
    JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray();
    ArrayList<String> listEmail = new ArrayList<>();
    if (sportsArray != null) {
        for (int i = 0; i < sportsArray.size(); i++) {
            listEmail.add(sportsArray.get(i).getAsString());
        }
    }

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    String addresses = "";
    for (int i = 0; i < listEmail.size(); i++) {
        if (i < listEmail.size() - 1) {
            addresses = addresses + listEmail.get(i) + ",";
        } else {
            addresses = addresses + listEmail.get(i);
        }
    }

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));

    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    try {
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("sent");
    return true;
}

From source file:FirstStatMain.java

private void btnsendemailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsendemailActionPerformed
    final String senderemail = txtEmailfrom.getText();
    final String sendPass = txtPassword.getText();
    String send_to = txtEmailto.getText();
    String email_sub = txtemailsbj.getText();
    String email_body = tABody.getText();

    Properties prop = new Properties();
    prop.put("mail.smtp.host", "smtp.gmail.com");
    prop.put("mail.smtp.socketFactory.port", "465");
    prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    prop.put("mail.smtp.auth", "true");
    prop.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
        @Override/*  w w  w  .j a v a2  s  .c o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderemail, sendPass);
        }
    });
    try {
        /* Message Header*/
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(senderemail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(send_to));
        message.setSubject(email_sub);
        /*setting text message*/
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(email_body);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        /*attaching file*/
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txtattachmentname.getText());
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc//  w  w  w . ja va 2 s . c  o  m
 */
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream contentInputStream;
    try {
        try {
            try {
                contentInputStream = getContentInputStream(message.messageUrl);
            } catch (UnknownHostException e) {
                // failover for misconfigured Exchange server, replace host name in url
                restoreHostName = true;
                contentInputStream = getContentInputStream(message.messageUrl);
            }
        } catch (HttpNotFoundException e) {
            LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
            contentInputStream = getContentInputStream(message.permanentUrl);
        }

        try {
            IOUtil.write(contentInputStream, baos);
        } finally {
            contentInputStream.close();
        }

    } catch (LoginTimeoutException e) {
        // throw error on expired session
        LOGGER.warn(e.getMessage());
        throw e;
    } catch (IOException e) {
        LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl
                + ", trying to rebuild from properties");

        try {
            DavPropertyNameSet messageProperties = new DavPropertyNameSet();
            messageProperties.add(Field.getPropertyName("contentclass"));
            messageProperties.add(Field.getPropertyName("message-id"));
            messageProperties.add(Field.getPropertyName("from"));
            messageProperties.add(Field.getPropertyName("to"));
            messageProperties.add(Field.getPropertyName("cc"));
            messageProperties.add(Field.getPropertyName("subject"));
            messageProperties.add(Field.getPropertyName("date"));
            messageProperties.add(Field.getPropertyName("htmldescription"));
            messageProperties.add(Field.getPropertyName("body"));
            PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl),
                    messageProperties, 0);
            DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
            MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
            if (responses.getResponses().length > 0) {
                MimeMessage mimeMessage = new MimeMessage((Session) null);

                DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
                String propertyValue = getPropertyIfExists(properties, "contentclass");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Content-class", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "date");
                if (propertyValue != null) {
                    mimeMessage.setSentDate(parseDateFromExchange(propertyValue));
                }
                propertyValue = getPropertyIfExists(properties, "from");
                if (propertyValue != null) {
                    mimeMessage.addHeader("From", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "to");
                if (propertyValue != null) {
                    mimeMessage.addHeader("To", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "cc");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Cc", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "subject");
                if (propertyValue != null) {
                    mimeMessage.setSubject(propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "htmldescription");
                if (propertyValue != null) {
                    mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
                } else {
                    propertyValue = getPropertyIfExists(properties, "body");
                    if (propertyValue != null) {
                        mimeMessage.setText(propertyValue);
                    }
                }
                mimeMessage.writeTo(baos);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (DavException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        // other exception
        if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
            LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: "
                    + message.permanentUrl);
            try {
                message.delete();
            } catch (IOException ioe) {
                LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
            }
            throw e;
        }
    }

    return baos.toByteArray();
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* use this method to obtain a mimemessage with the file wrapped in it.
*
* @param  filename filename of the file.
* @param  data the file in bytes./*  w w  w. j av  a2 s  .  c  o m*/
* @return a byte array of the mimemessage.
*/
static public byte[] wrapInMimeMessage(String filename, byte[] data) throws Exception {
    MimeMessage mimemessage = new MimeMessage(javax.mail.Session.getDefaultInstance(new Properties(), null));
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    mimemessage.setContent(multipart);
    mimemessage.saveChanges();

    // finally pipe to an array so we can conver to string
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mimemessage.writeTo(bos);
    return bos.toString().getBytes();
}