Example usage for javax.mail Message setHeader

List of usage examples for javax.mail Message setHeader

Introduction

In this page you can find the example usage for javax.mail Message setHeader.

Prototype

public void setHeader(String header_name, String header_value) throws MessagingException;

Source Link

Document

Set the value for this header_name.

Usage

From source file:msgsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;// w w  w.ja v a 2s .  co  m
    String mailer = "msgsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

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

From source file:smtpsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from ww w.  ja  v  a  2s  . c  o m
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    boolean ssl = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            ssl = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         * 
         * Transport.send(msg);
         * 
         * But we're going to use some SMTP-specific features for demonstration
         * purposes so we need to manage the Transport object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command.//from   ww  w  .  j av  a 2 s  .  c om
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

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

/**
 * Send a HTML formated message./*from www  .  jav  a 2 s.  c o  m*/
 * @param strRecipientsTo
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occured
 */
protected static void sendMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc,
        String strSenderName, String strSenderEmail, String strSubject, String strMessage, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);

    msg.setHeader(HEADER_NAME, HEADER_VALUE);
    // Message body formated in HTML
    msg.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    sendMessage(msg, transport);
}

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

/**
 * Send a calendar message./*  w  ww . ja v  a  2 s.c o m*/
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

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

/**
 * Send a Multipart text message with attached files. FIXME: use
 * prepareMessage method//from  w  w w. j a  v  a 2  s  .  co  m
 *
 * @param strRecipientsTo
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param fileAttachements
 *            The list of attached files
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occured
 */
protected static void sendMultipartMessageText(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session)
        throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

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

/**
 * Send a Multipart HTML message with the attachements associated to the
 * message and attached files. FIXME: use prepareMessage method
 *
 * @param strRecipientsTo//from   w  w w  .jav  a 2s .c o m
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param urlAttachements
 *            The List of UrlAttachement Object, containing the URL of
 *            attachments associated with their content-location.
 * @param fileAttachements
 *            The list of files attached
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements,
        Transport transport, Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty()))
            ? new MimeMultipart(MULTIPART_RELATED)
            : new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    if (urlAttachements != null) {
        ByteArrayDataSource urlByteArrayDataSource;

        for (UrlAttachment urlAttachement : urlAttachements) {
            urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement);

            if (urlByteArrayDataSource != null) {
                msgBodyPart = new MimeBodyPart();
                // Fill this part, then add it to the root part with the
                // good headers
                msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource));
                msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation());
                multipart.addBodyPart(msgBodyPart);
            }
        }
    }

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:ips1ap101.ejb.core.mail.MailerBean.java

@Override
public Message sendMessage(String addressList, String subject, String text) throws MessagingException {
    if (EA.isMailingEnabled()) {
    } else {/*w  w w .ja va 2 s  .  c o m*/
        return null;
    }
    if (StringUtils.isBlank(addressList)) {
        throw new InvalidParameterException("addressList");
    }
    if (StringUtils.isBlank(subject)) {
        throw new InvalidParameterException("subject");
    }
    if (StringUtils.isBlank(text)) {
        throw new InvalidParameterException("text");
    }
    Address[] internetAddressList = InternetAddress.parse(addressList, false);
    Date timeStamp = new Date();
    Message message = new MimeMessage(session);
    message.setFrom();
    message.setHeader("X-Mailer", "JavaMail");
    message.setRecipients(Message.RecipientType.TO, internetAddressList);
    message.setSentDate(timeStamp);
    message.setSubject(subject);
    message.setText(text);
    Transport.send(message);
    return message;
}

From source file:esg.node.components.notification.ESGNotifier.java

private boolean sendNotification(String userid, String userAddress, String messageText) {
    Message msg = null;
    boolean success = false;
    String myAddress = null;//ww  w. jav a2  s. co  m

    try {
        msg = new MimeMessage(session);
        msg.setHeader("X-Mailer", "ESG DataNode IshMailer");
        msg.setSentDate(new Date());
        myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov");
        msg.setFrom(new InternetAddress(myAddress));
        msg.setSubject(subject + "ESG File Update Notification");

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress));
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress));

        msg.setText(messageText);

        Transport.send(msg);
        success = true;
    } catch (MessagingException ex) {
        log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject
                + ")\n" + messageText + "\n", ex);
    }

    msg = null; //gc niceness

    return success;
}

From source file:de.fzi.ALERT.actor.ActionActuator.MailService.java

public void sendEmail(Authenticator auth, String address, String subject, String content) {
    try {//w  w w.j av  a 2 s  . c  om
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, auth);
        // -- Create a new message --
        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // -- Set the subject and body text --
        msg.setSubject(subject);
        msg.setText(content);

        // -- Set some other header information --
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());

        // -- Send the message --
        Transport.send(msg);

        System.out.println("An announce Mail has been send to " + address);
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}