Example usage for javax.mail.internet MimeMessage saveChanges

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

Introduction

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

Prototype

@Override
public void saveChanges() throws MessagingException 

Source Link

Document

Updates the appropriate header fields of this message to be consistent with the message's contents.

Usage

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail./* w  ww .j a v a 2  s .  c  om*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null && Config.SEND_MAIL_FROM_USER) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;// w w w  . j a va 2s .  co m
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

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./*from ww  w. ja  v  a2  s .co  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();
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/*w  ww  .jav  a 2s .co m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.buzzdavidson.spork.client.OWAClient.java

/**
 * Fetch the body of the email message given a message URL.
 *
 * @param message Mime message to add body to
 * @param messageUrl URL of message (OWA WebDav)
 *//*from  w  w  w . j a  v a 2 s .  c  o m*/
private void populateMessage(MimeMessage message, String messageUrl) {
    GetMethod get = new GetMethod(messageUrl);
    get.setRequestHeader("Translate", "F");
    try {
        logger.info("Requesting message body via url [" + messageUrl + "]");
        int status = client.executeMethod(get);
        if (logger.isDebugEnabled()) {
            logger.debug("Message request returned status code [" + status + "]");
        }
        if (status == HttpStatus.SC_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            String contentType = OWAUtils.getSingleHeader(message, PARAM_CONTENT_TYPE);
            String contentEncoding = OWAUtils.getSingleHeader(message, PARAM_CONTENT_ENCODING);
            boolean needContentType = (contentType == null || contentType.length() < 1);

            // first set of entries are headers, followed by empty line.  skip to first empty line.
            for (String line; (line = in.readLine()) != null;) {
                if (line != null && line.trim().length() == 0) {
                    break;
                }
            }

            StringBuffer buf = new StringBuffer();
            for (String line; (line = in.readLine()) != null;) {
                buf.append(line);
                buf.append(NEWLINE);
            }

            if (needContentType || contentType.contains(CONTENT_TYPE_TEXT_PLAIN)) {
                // OWA sometimes reports XML or HTML content as "text/plain"; check for this.

                if (logger.isDebugEnabled()) {
                    logger.debug("checking content encoding");
                }
                byte[] blob = buf.toString().getBytes();
                if (logger.isDebugEnabled()) {
                    logger.debug("blob length is " + blob.length + " bytes");
                }
                if (contentEncoding.equals(BASE_64_ENCODING)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is base64 encoded, decoding");
                    }
                    byte[] newblob = Base64.decodeBase64(blob);
                    if (logger.isDebugEnabled()) {
                        logger.debug("decoded blob length is " + newblob.length + " bytes");
                    }
                    String data = new String(newblob);
                    buf = new StringBuffer(data);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is encoded with [" + contentEncoding + "], not decoding");
                    }
                }
                contentType = determineContentType(buf, message);
            }

            if (wantDiagnostics) {
                buf.append(NEWLINE);
                buf.append("-------------------------------------");
                buf.append(NEWLINE);
                buf.append("SPORK Data");
                buf.append(NEWLINE);
                buf.append("content-encoding: " + contentEncoding);
                buf.append(NEWLINE);
                buf.append("content-type: " + contentType);
                if (needContentType) {
                    buf.append(" (calculated) " + contentType);
                    buf.append(" Message processed "
                            + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));
                }
            }

            if (needContentType) {
                buf = cleanupBuffer(buf);
            }

            buf.append(NEWLINE);
            message.setText(buf.toString());
            int len = buf.length();
            message.setHeader(PARAM_CONTENT_LENGTH, Integer.valueOf(len).toString()); // close enough :)
            if (contentType != null && contentType.length() > 0) {
                message.setHeader(PARAM_CONTENT_TYPE, contentType);
            }
            message.saveChanges();
        }
    } catch (HttpException ex) {
        logger.error("Received HttpException fetching message body", ex);
    } catch (UnsupportedEncodingException ex) {
        logger.error("Received UnsupportedEncodingException fetching message body", ex);
    } catch (IOException ex) {
        logger.error("Received IOException fetching message body", ex);
    } catch (MessagingException ex) {
        logger.error("Received MessagingException fetching message body", ex);
    }
}

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();//www  .j  ava 2  s  .  c  o  m
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email)
        throws MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Core.hasAdminEmail()) {
        return false;
    } else if (!Domain.isEmail(email)) {
        return false;
    } else if (NoReply.contains(email, true)) {
        return false;
    } else {/*from w w w .  j av a 2s.  c  o m*/
        try {
            Server.logDebug("sending unblock by e-mail.");
            User user = User.get(email);
            InternetAddress[] recipients;
            if (user == null) {
                recipients = InternetAddress.parse(email);
            } else {
                recipients = new InternetAddress[1];
                recipients[0] = user.getInternetAddress();
            }
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminInternetAddress());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Chave de desbloqueio SPFBL";
            } else {
                subject = "Unblocking key SPFBL";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildConfirmAction(builder, "Desbloquear IP", url,
                        "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net",
                        "http://spfbl.net/");
            } else {
                buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL",
                        "SPFBL.net", "http://spfbl.net/en/");
            }
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL");
                buildText(builder,
                        "Se voc  o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:");
            } else {
                buildMessage(builder, "Unblock of IP " + ip + " at DNSBL");
                buildText(builder,
                        "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 30000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

public static boolean enviarOTP(Locale locale, User user) {
    if (locale == null) {
        Server.logError("no locale defined.");
        return false;
    } else if (!Core.hasOutputSMTP()) {
        Server.logError("no SMTP account to send TOTP.");
        return false;
    } else if (!Core.hasAdminEmail()) {
        Server.logError("no admin e-mail to send TOTP.");
        return false;
    } else if (user == null) {
        Server.logError("no user definied to send TOTP.");
        return false;
    } else if (NoReply.contains(user.getEmail(), true)) {
        Server.logError("cannot send TOTP because user is registered in noreply.");
        return false;
    } else {/*  www  . j a  v  a 2 s  .  c o m*/
        try {
            Server.logDebug("sending TOTP by e-mail.");
            String secret = user.newSecretOTP();
            InternetAddress[] recipients = new InternetAddress[1];
            recipients[0] = user.getInternetAddress();
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminInternetAddress());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Chave TOTP do SPFBL";
            } else {
                subject = "SPFBL TOTP key";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildMessage(builder,
                        "Sua chave <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> no sistema SPFBL em "
                                + Core.getHostname());
                buildText(builder,
                        "Carregue o QRCode abaixo em seu Google Authenticator ou em outro aplicativo <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> de sua preferncia.");
                builder.append("      <div id=\"divcaptcha\">\n");
                builder.append("        <img src=\"cid:qrcode\"><br>\n");
                builder.append("        ");
                builder.append(secret);
                builder.append("\n");
                builder.append("      </div>\n");
            } else {
                buildMessage(builder,
                        "Your <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> key in SPFBL system at "
                                + Core.getHostname());
                buildText(builder,
                        "Load QRCode below on your Google Authenticator or on other application <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> of your choice.");
                builder.append("      <div id=\"divcaptcha\">\n");
                builder.append("        <img src=\"cid:qrcode\"><br>\n");
                builder.append("        ");
                builder.append(secret);
                builder.append("\n");
                builder.append("      </div>\n");
            }
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Making QRcode part.
            MimeBodyPart qrcodePart = new MimeBodyPart();
            String code = "otpauth://totp/" + Core.getHostname() + ":" + user.getEmail() + "?" + "secret="
                    + secret + "&" + "issuer=" + Core.getHostname();
            File qrcodeFile = Core.getQRCodeTempFile(code);
            qrcodePart.attachFile(qrcodeFile);
            qrcodePart.setContentID("<qrcode>");
            qrcodePart.addHeader("Content-Type", "image/png");
            qrcodePart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            content.addBodyPart(qrcodePart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            boolean sent = Core.sendMessage(message, 5000);
            qrcodeFile.delete();
            return sent;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueio(String url, String remetente, String destinatario)
        throws SendFailedException, MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Domain.isEmail(destinatario)) {
        return false;
    } else if (NoReply.contains(destinatario, true)) {
        return false;
    } else {//ww w  .  j  ava 2  s.  c om
        try {
            Server.logDebug("sending unblock by e-mail.");
            Locale locale = User.getLocale(destinatario);
            InternetAddress[] recipients = InternetAddress.parse(destinatario);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.setReplyTo(InternetAddress.parse(remetente));
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Solicitao de envio SPFBL";
            } else {
                subject = "SPFBL send request";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este e-mail foi gerado pois nosso servidor recusou uma ou mais mensagens do remetente "
                                + remetente
                                + " e o mesmo requisitou que seja feita a liberao para que novos e-mails possam ser entregues a voc.");
                buildText(builder, "Se voc deseja receber e-mails de " + remetente
                        + ", acesse o endereo abaixo e para iniciar o processo de liberao:");
            } else {
                buildText(builder,
                        "This email was generated because our server has refused one or more messages from the sender "
                                + remetente
                                + " and the same sender has requested that the release be made for new emails can be delivered to you.");
                buildText(builder, "If you wish to receive emails from " + remetente
                        + ", access the address below and to start the release process:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 5000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarConfirmacaoDesbloqueio(String destinatario, String remetente, Locale locale) {
    if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isEmail(remetente)
            && !NoReply.contains(remetente, true)) {
        try {/*from  w w  w  .j a  v  a  2 s . c om*/
            Server.logDebug("sending unblock confirmation by e-mail.");
            InternetAddress[] recipients = InternetAddress.parse(remetente);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.setReplyTo(InternetAddress.parse(destinatario));
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Confirmao de desbloqueio SPFBL";
            } else {
                subject = "SPFBL unblocking confirmation";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder, "O destinatrio '" + destinatario
                        + "' acabou de liberar o recebimento de suas mensagens.");
                buildText(builder, "Por favor, envie novamente a mensagem anterior.");
            } else {
                buildText(builder,
                        "The recipient '" + destinatario + "' just released the receipt of your message.");
                buildText(builder, "Please send the previous message again.");
            }
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 5000);
        } catch (MessagingException ex) {
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    } else {
        return false;
    }
}