Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:it.infn.ct.nuclemd.Nuclemd.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {/*w w  w . j a  v  a  2s  . com*/

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException ex) {
        Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

static public String sendMailShowResult(String host, int port, String fromname, String from, String to,
        String subject, String msg) throws Exception {
    String response = "OK";

    SMTPTransport transport = null;//from   w w  w .  jav  a2  s  . c o m
    boolean ok = true;

    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");
        props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original
        props.put("mail.smtp.timeout", "60000");
        props.put("mail.smtp.quitwait", "false");

        javax.mail.Session session = javax.mail.Session.getInstance(props);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);
        if (fromname == null || fromname.isEmpty()) {
            message.setFrom(new InternetAddress(from));
        } else {
            message.setFrom(new InternetAddress(from, fromname));
        }
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);
        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

    } catch (Exception e) {
        e.printStackTrace();
        ok = false;
    } finally {

        try {
            if (!ok) {
                response = "SENDING FAILED:" + transport.getLastServerResponse();
            } else {
                response = "SENDING SUCCESS:" + transport.getLastServerResponse();
            }

            transport.close();

        } catch (Exception f) {

        }

    }
    return response;
}

From source file:immf.ImodeForwardMail.java

@Override
public void buildMimeMessage() throws EmailException {
    super.buildMimeMessage();
    MimeMessage msg = this.getMimeMessage();
    try {/*  ww  w  . jav  a  2 s .  c o m*/
        msg.setHeader("X-Mailer", ServerMain.Version);

        if (!this.conf.isRewriteAddress()) {
            // ??imode????????
            msg.setHeader("Resent-From", this.conf.getSmtpMailAddress());
            if (!this.conf.getForwardTo().isEmpty()) {
                msg.setHeader("Resent-To", StringUtils.join(this.conf.getForwardTo(), ","));
            }
            if (!this.conf.getForwardCc().isEmpty()) {
                msg.setHeader("Resent-Cc", StringUtils.join(this.conf.getForwardCc(), ","));
            }
            if (!this.conf.getForwardBcc().isEmpty()) {
                msg.setHeader("Resent-Bcc", StringUtils.join(this.conf.getForwardBcc(), ","));
            }
            SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US);
            msg.setHeader("Resent-Date", df.format(new Date()));
            msg.setHeader("Date", df.format(this.imm.getTimeDate()));

            msg.removeHeader("To");
            msg.removeHeader("Cc");
            msg.removeHeader("Bcc");

            List<InternetAddress> tolist = new ArrayList<InternetAddress>();
            List<InternetAddress> cclist = new ArrayList<InternetAddress>();

            boolean useMyAddress = false;
            if (this.imm.getFolderId() != ImodeNetClient.FolderIdSent) {
                if (this.conf.isHideMyaddr()) {
                    if (this.imm.getToAddrList().size() == 0) {
                        useMyAddress = true;
                    }
                } else {
                    useMyAddress = true;
                }
            }
            if (useMyAddress) {
                switch (this.imm.getRecvType()) {
                case ImodeMail.RECV_TYPE_TO:
                    tolist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_CC:
                    cclist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_BCC:
                    break;
                }
            }
            tolist.addAll(this.imm.getToAddrList());
            cclist.addAll(this.imm.getCcAddrList());

            msg.setHeader("To", InternetAddress.toString(tolist.toArray(new InternetAddress[0])));

            if (this.imm.getCcAddrList().size() > 0) {
                msg.setHeader("Cc", InternetAddress.toString(cclist.toArray(new InternetAddress[0])));
            }

            msg.setFrom(this.imm.getFromAddr());
        }

        String subject = null;
        if (imm.getFolderId() == ImodeNetClient.FolderIdSent) {
            subject = conf.getSentSubjectAppendPrefix() + imm.getSubject() + conf.getSentSubjectAppendSuffix();
        } else {
            subject = conf.getSubjectAppendPrefix() + imm.getSubject() + conf.getSubjectAppendSuffix();
        }
        if (conf.isSubjectEmojiReplace()) {
            subject = EmojiUtil.replaceToLabel(subject);
        }

        if (ImodeForwardMail.goomojiSubjectCharConv != null) {
            String goomojiSubject = ImodeForwardMail.goomojiSubjectCharConv.convert(subject);
            msg.setHeader("X-Goomoji-Source", "docomo_ne_jp");
            msg.setHeader("X-Goomoji-Subject", Util.encodeGoomojiSubject(goomojiSubject));
        }

        subject = ImodeForwardMail.subjectCharConv.convert(subject);
        msg.setSubject(MimeUtility.encodeText(subject, this.charset, "B"));

        if (this.conf.getContentTransferEncoding() != null) {
            msg.setHeader("Content-Transfer-Encoding", this.conf.getContentTransferEncoding());
        }

    } catch (Exception e) {
        log.warn(e);
    }
}

From source file:it.infn.ct.wrf.Wrf.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {/*w w w .j ava 2  s  . c o m*/

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Creates the IMAP messages to be sent. Looks up access (email & pwd) from
 * LDAP, sets the values and returns the messages to be sent.
 * /*from  w  w  w . j a v  a  2 s  . c  o m*/
 * @param session Mail session 
 * @param emailAddr From email address
 * @param request Request from PS
 * @return Array of messages
 * @throws Exception 
 */
private Message[] createMessage(Session session, String emailAddr, SetMessageRequestType request)
        throws Exception {

    /*
    //DBG ONLY - Check about CC entry.
    List<String> ctlist = request.getContactTo();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: TO="+ ctlist.get(0));
    }
    ctlist = request.getContactCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: CC="+ ctlist.get(0));
    }
    ctlist = request.getContactBCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: BCC="+ ctlist.get(0));
    }
    */
    MimeMessage message = new MimeMessage(session);

    if (!CommonUtil.listNullorEmpty(request.getContactTo())) {
        message.setRecipients(Message.RecipientType.TO, getInetAddresses(request.getContactTo())); //getInetAddresses(request, "To"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactCC())) {
        message.setRecipients(Message.RecipientType.CC, getInetAddresses(request.getContactCC())); //getInetAddresses(request, "CC"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactBCC())) {
        message.setRecipients(Message.RecipientType.BCC, getInetAddresses(request.getContactBCC())); //getInetAddresses(request, "BCC"));
    }

    message.setSubject(request.getSubject());

    // Adding headers doesn't seem to be supported currently in zimbra. 
    // Adding patientId to body instead temporarily 
    // message.addHeader("X-PATIENTID", request.getPatientId());
    StringBuilder sb = new StringBuilder();

    // Only add in PATIENTID first line if there is a patientId in session.
    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        sb.append("PATIENTID=").append(request.getPatientId()).append("\n");
    }

    if (CommonUtil.strNullorEmpty(request.getBody())) {
        sb.append("");
    } else {
        sb.append(request.getBody());
    }

    message.setContent(sb.toString(), "text/plain");
    message.setFrom(new InternetAddress(emailAddr));
    message.setSentDate(new Date());

    List<String> labelList = request.getLabels();
    if (labelList.size() > 0) {
        String label = labelList.get(0);
        if (label.equalsIgnoreCase("starred")) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    }
    Message[] msgArr = new Message[1];
    msgArr[0] = message;
    return msgArr;
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

private MimeMessage prepareMimeMessage(MimeMessage mimeMessage, Node node, String template, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws AddressException, MessagingException, ValueFormatException,
        PathNotFoundException, RepositoryException, UnsupportedEncodingException {

    if (replyTo != null) {
        mimeMessage.setReplyTo(convertToInternetAddress(replyTo));
    } else {/*from w  ww .j  a  va  2s  .  co  m*/
        if (node != null && node.hasProperty("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(node.getProperty("replyTo").getString()));
        } else if (variables != null && variables.containsKey("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(variables.get("replyTo")));
        }
    }
    if (date == null) {
        if (node != null && node.hasProperty("mailDate")) {
            mimeMessage.setSentDate(node.getProperty("mailDate").getDate().getTime());
        } else if (variables != null && variables.containsKey("mailDate")) {
            mimeMessage.setSentDate((Date) variables.get("mailDate"));
        } else {
            mimeMessage.setSentDate(new Date());
        }
    } else {
        mimeMessage.setSentDate(date);
    }

    if (subject != null) {
        mimeMessage.setSubject(MimeUtility.encodeText(subject, configurator.getEncoding(), "Q"));
    } else {
        if (node != null && node.hasProperty("subject")) {
            mimeMessage.setSubject(MimeUtility.encodeText(node.getProperty("subject").getString(),
                    configurator.getEncoding(), "Q"));
        } else if (variables != null && variables.containsKey("subject")) {
            mimeMessage.setSubject(
                    MimeUtility.encodeText((String) variables.get("subject"), configurator.getEncoding(), "Q"));
        }
    }

    if (from != null) {
        mimeMessage.setFrom(convertToInternetAddress(from)[0]);
    } else {
        if (node != null && node.hasProperty("from")) {
            mimeMessage.setFrom(convertToInternetAddress(node.getProperty("from").getString())[0]);
        } else if (variables != null && variables.containsKey("from")) {
            mimeMessage.setFrom(convertToInternetAddress(variables.get("from"))[0]);
        }
    }

    if (to != null) {
        mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(to));
    } else {
        if (node != null && node.hasProperty("to")) {
            if (node.getProperty("to").isMultiple()) {
                Value[] values = node.getProperty("to").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.TO,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.TO,
                        convertToInternetAddress(node.getProperty("to").getString()));
            }
        } else if (variables != null && variables.containsKey("to")) {
            mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(variables.get("to")));
        }

    }

    if (cc != null) {
        mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(cc));
    } else {
        if (node != null && node.hasProperty("cc")) {
            if (node.getProperty("cc").isMultiple()) {
                Value[] values = node.getProperty("cc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.CC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.CC,
                        convertToInternetAddress(node.getProperty("cc").getString()));
            }
        } else if (variables != null && variables.containsKey("cc")) {
            mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(variables.get("cc")));
        }
    }

    if (bcc != null) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(bcc));
    } else {
        if (node != null && node.hasProperty("bcc")) {
            if (node.getProperty("bcc").isMultiple()) {
                Value[] values = node.getProperty("bcc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.BCC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.BCC,
                        convertToInternetAddress(node.getProperty("bcc").getString()));
            }
        } else if (variables != null && variables.containsKey("bcc")) {
            mimeMessage.addRecipients(Message.RecipientType.BCC,
                    convertToInternetAddress(variables.get("bcc")));
        }
    }
    return mimeMessage;
}

From source file:library.Form_Library.java

License:asdf

public void sendFromGMail(String from, String pass, String to, String subject, String body) {
    this.taBaoCao.append("Sent to " + to + " successfully.\n");
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {//from  ww  w . j  a  v a 2 s .c  o m
        message.setFrom(new InternetAddress(from));
        InternetAddress toAddress = new InternetAddress();

        // To get the array of addresses
        //            for( int i = 0; i < to.length; i++ ) {
        toAddress = new InternetAddress(to);
        //            }

        //            for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress);
        //            }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        System.out.print("Successfully Sent" + "\n");
        transport.close();
    } catch (AddressException ae) {
        ae.printStackTrace();
    } catch (MessagingException me) {
        me.printStackTrace();
    }
}

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 o m*/
            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;
    }
}

From source file:net.spfbl.spf.SPF.java

private static boolean enviarLiberacao(String url, String remetente, String destinatario) {
    if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isValidEmail(remetente)
            && Domain.isValidEmail(destinatario) && url != null && !NoReply.contains(remetente, true)) {
        try {//from w  w  w  .j  a v a 2 s.  c  o m
            Server.logDebug("sending liberation by e-mail.");
            Locale locale = Core.getDefaultLocale(remetente);
            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.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Liberao de recebimento";
            } else {
                subject = "Receiving release";
            }
            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");
            ServerHTTP.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");
            ServerHTTP.buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                ServerHTTP.buildText(builder, "O recebimento da sua mensagem para " + destinatario
                        + " est sendo atrasado por suspeita de SPAM.");
                ServerHTTP.buildText(builder,
                        "Para que sua mensagem seja liberada, acesse este link e resolva o desafio reCAPTCHA:");
            } else {
                ServerHTTP.buildText(builder, "Receiving your message to " + destinatario
                        + " is being delayed due to suspected SPAM.");
                ServerHTTP.buildText(builder,
                        "In order for your message to be released, access this link and resolve the reCAPTCHA:");
            }
            ServerHTTP.buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            ServerHTTP.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 = ServerHTTP.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) {
            return false;
        } catch (SendFailedException ex) {
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    } else {
        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 {//w  w  w  . j av  a 2s .  c o m
        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;
        }
    }
}