Example usage for javax.mail Message addHeader

List of usage examples for javax.mail Message addHeader

Introduction

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

Prototype

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

Source Link

Document

Add this value to the existing values for this header_name.

Usage

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from   w w  w. ja va2s  .  co  m*/
 *
 * @param message DOCUMENT ME!
 * @param headers DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void addHeaders(Message message, InternetHeaders headers) throws MessagingException {
    Header xheader;
    Enumeration xe = headers.getAllHeaders();

    for (; xe.hasMoreElements();) {
        xheader = (Header) xe.nextElement();
        message.addHeader(xheader.getName(), xheader.getValue());
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {//from  ww  w . ja  v a 2  s.c  om
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {/*from w  w w .  ja  va2s.c  o  m*/
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw Context.reportRuntimeError("sendMail: " + e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call sendMail requires 5 arguments.");
    }
}

From source file:org.forumj.email.FJEMail.java

public static void sendMail(String to, String from, String host, String subject, String text)
        throws ConfigurationException, AddressException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    String mailDebug = FJConfiguration.getConfig().getString("mail.debug");
    props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
    Session session = Session.getInstance(props);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = { new InternetAddress(to) };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.addHeader("charset", "UTF-8");
    msg.setSubject(subject);/*from   www .  j  av a2 s .c  o  m*/
    msg.setSentDate(new Date());
    msg.setDataHandler(new DataHandler(new HTMLDataSource(text)));
    Transport.send(msg);
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

public void start(PipelineContext pipelineContext) {
    try {/*  w  ww . ja  v a 2s  .  c  o  m*/
        final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA);
        final Element messageElement = dataDocument.getRootElement();

        // Get system id (will likely be null if document is generated dynamically)
        final LocationData locationData = (LocationData) messageElement.getData();
        final String dataInputSystemId = locationData.getSystemID();

        // Set SMTP host
        final Properties properties = new Properties();
        final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST);

        if (testSmtpHostProperty != null) {
            // Test SMTP Host from properties overrides the local configuration
            properties.setProperty("mail.smtp.host", testSmtpHostProperty);
        } else {
            // Try regular config parameter and property
            String host = messageElement.element("smtp-host").getTextTrim();
            if (host != null && !host.equals("")) {
                // Precedence goes to the local config parameter
                properties.setProperty("mail.smtp.host", host);
            } else {
                // Otherwise try to use a property
                host = getPropertySet().getString(EMAIL_SMTP_HOST);
                if (host == null)
                    host = getPropertySet().getString(EMAIL_HOST_DEPRECATED);
                if (host == null)
                    throw new OXFException("Could not find SMTP host in configuration or in properties");
                properties.setProperty("mail.smtp.host", host);

            }
        }

        // Create session
        final Session session;
        {
            // Get credentials
            final String usernameTrimmed;
            final String passwordTrimmed;
            {
                final Element credentials = messageElement.element("credentials");
                if (credentials != null) {
                    final Element usernameElement = credentials.element("username");
                    final Element passwordElement = credentials.element("password");
                    usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim()
                            : null;
                    passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : "";
                } else {
                    usernameTrimmed = null;
                    passwordTrimmed = null;
                }
            }

            // Check if credentials are supplied
            if (StringUtils.isNotEmpty(usernameTrimmed)) {
                // NOTE: A blank username doesn't trigger authentication

                if (logger.isInfoEnabled())
                    logger.info("Authentication");
                // Set the auth property to true
                properties.setProperty("mail.smtp.auth", "true");

                if (logger.isInfoEnabled())
                    logger.info("Username: " + usernameTrimmed);

                // Create an authenticator
                final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed);

                // Create session with authenticator
                session = Session.getInstance(properties, authenticator);
            } else {
                if (logger.isInfoEnabled())
                    logger.info("No Authentication");
                session = Session.getInstance(properties);
            }
        }

        // Create message
        final Message message = new MimeMessage(session);

        // Set From
        message.addFrom(createAddresses(messageElement.element("from")));

        // Set To
        String testToProperty = getPropertySet().getString(EMAIL_TEST_TO);
        if (testToProperty == null)
            testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED);

        if (testToProperty != null) {
            // Test To from properties overrides local configuration
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty));
        } else {
            // Regular list of To elements
            for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) {
                final InternetAddress[] addresses = createAddresses(toElement);
                message.addRecipients(Message.RecipientType.TO, addresses);
            }
        }

        // Set Cc
        for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) {
            final InternetAddress[] addresses = createAddresses(ccElement);
            message.addRecipients(Message.RecipientType.CC, addresses);
        }

        // Set Bcc
        for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) {
            final InternetAddress[] addresses = createAddresses(bccElement);
            message.addRecipients(Message.RecipientType.BCC, addresses);
        }

        // Set headers if any
        for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) {
            final String headerName = headerElement.element("name").getTextTrim();
            final String headerValue = headerElement.element("value").getTextTrim();

            // NOTE: Use encodeText() in case there are non-ASCII characters
            message.addHeader(headerName,
                    MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null));
        }

        // Set the email subject
        // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it
        // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode.
        // The result is pure ASCII so that setSubject() will not attempt to re-encode it.
        message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(),
                DEFAULT_CHARACTER_ENCODING, null));

        // Handle body
        final Element textElement = messageElement.element("text");
        final Element bodyElement = messageElement.element("body");

        if (textElement != null) {
            // Old deprecated mechanism (simple text body)
            message.setText(textElement.getStringValue());
        } else if (bodyElement != null) {
            // New mechanism with body and parts
            handleBody(pipelineContext, dataInputSystemId, message, bodyElement);
        } else {
            throw new OXFException("Main text or body element not found");// TODO: location info
        }

        // Send message
        final Transport transport = session.getTransport("smtp");
        Transport.send(message);
        transport.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message
    if (ArgList.length == 5) {

        try {/*w w w  .  j  ava2  s . co m*/
            // Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String[] strArrRecipients = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent(ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message
    if (ArgList.length == 5) {

        try {//from  w  w  w.  j  av a  2s .  c o m
            // Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String[] strArrRecipients = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent(ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw Context.reportRuntimeError("sendMail: " + e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call sendMail requires 5 arguments.");
    }
}