Example usage for javax.mail.internet MimeMessage addRecipients

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

Introduction

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

Prototype

public void addRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Add the given addresses to the specified recipient type.

Usage

From source file:com.sat.common.CustomReport.java

/**
 * Sendmail./*from  w ww  .  jav a 2  s.c o m*/
 * 
 * @param msg
 *            the msg
 * @throws AddressException
 *             the address exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {

    ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager();
    miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms");
    Validate miscValidate = new Validate();

    String from = miscValidate.readsystemvariable("MAIL.FROM");
    String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST");
    String to = miscValidate.readsystemvariable("MAIL.TO");

    String subject = miscValidate.readsystemvariable("MAIL.SUBJECT");
    String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL");

    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, personal));

        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:org.apache.lens.server.query.QueryEndNotifier.java

/** Send mail.
 *
 * @param host                      the host
 * @param port                      the port
 * @param email                     the email
 * @param mailSmtpTimeout           the mail smtp timeout
 * @param mailSmtpConnectionTimeout the mail smtp connection timeout */
public static void sendMail(String host, String port, Email email, int mailSmtpTimeout,
        int mailSmtpConnectionTimeout) throws Exception {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.timeout", mailSmtpTimeout);
    props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email.getFrom()));
    for (String recipient : email.getTo().trim().split("\\s*,\\s*")) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
    }/*from  w  w  w .ja va2 s. com*/
    if (email.getCc() != null && email.getCc().length() > 0) {
        for (String recipient : email.getCc().trim().split("\\s*,\\s*")) {
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient));
        }
    }
    message.setSubject(email.getSubject());
    message.setSentDate(new Date());

    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setText(email.getMessage());
    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messagePart);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * /*from  ww  w  .  j a v a  2 s .  co m*/
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String[] to, String[] cc, String[] bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));

        if (cc != null && cc.length != 0) {
            for (int i = cc.length - 1; i >= 0; i--) {
                msg.addRecipients(Message.RecipientType.CC, cc[i]);
            }
        }
        if (bcc != null && bcc.length != 0) {
            for (int i = bcc.length - 1; i >= 0; i--) {
                msg.addRecipients(Message.RecipientType.BCC, bcc[i]);
            }
        }
        if (to != null && to.length != 0) {
            for (int i = to.length - 1; i >= 0; i--) {
                msg.addRecipients(Message.RecipientType.TO, to[i]);
            }
        }
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Sends an email in text-format in iso-8859-1-encoding
 * /*from w  w  w . jav  a 2s  .c om*/
 * @param subject the subject of the new mail
 * @param message the content of the mail
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendMail(String subject, String message, String from, String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());
        msg.setText(message, "iso-8859-1");
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending mail: " + e.getLocalizedMessage());
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * /*from w ww. j a va2  s.c  o  m*/
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setText(alternativeTextMessage);
        multiPart.addBodyPart(bodyPart);

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlMessage, "text/html");
        multiPart.addBodyPart(bodyPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * /*from w  w  w.j  a  va  2  s .  c  om*/
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }/*from   ww  w  . java 2  s.c o  m*/

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Sends an email in text-format in iso-8859-1-encoding
 * //from w  ww.  j ava 2 s .  com
 * @param subject the subject of the new mail
 * @param message the content of the mail
 * @param from the sender-address
 * @param to the receiver-address(es)
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendMail(String subject, String message, String from, String[] to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        for (int i = to.length - 1; i >= 0; i--) {
            msg.addRecipients(Message.RecipientType.TO, to[i]);
        }
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());
        msg.setText(message, "iso-8859-1");
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending mail: " + e.getLocalizedMessage());
    }
}

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * Sendmail.//from www .  j a v a2  s . c  o m
 *
 * @param msg the msg
 * @throws AddressException the address exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {
    //Properties CustomReport_CONFIG = new Properties();
    //FileInputStream fn = new FileInputStream(System.getProperty("user.dir")+ "/src/it/resources/config.properties");
    //CustomReport_CONFIG.load(fn);
    String from = "automationreportmailer@cisco.com";
    // String from = "sitaut@cisco.com";
    //String host = System.getProperty("MAIL.SMTP.HOST");
    String host = "outbound.cisco.com";
    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    // String ecsip = CustomReport_CONFIG.getProperty("ecsip");
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from
        // ));
                , "Automation Report Mailer"));
        //message.addRecipients(Message.RecipientType.TO, System.getProperty("MAIL.TO"));
        //message.setSubject(System.getProperty("mail.subject"));

        message.addRecipients(Message.RecipientType.TO, "maparame@cisco.com");
        message.setSubject("VCS consle report");
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {//from   w  ww.  j a va  2 s  . co  m
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

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

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

        DataSource source = new FileDataSource(attachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(attachment.getName());
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}