Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    VitroRequest vreq = new VitroRequest(request);

    String confirmpage = "/confirmUserMail.jsp";
    String errpage = "/contact_err.jsp";
    String status = null; // holds the error status

    if (!FreemarkerEmailFactory.isConfigured(vreq)) {
        status = "This application has not yet been configured to send mail. "
                + "Email properties must be specified in the configuration properties file.";
        response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status);
        return;//  w  ww.  j  a  v a2  s  . c o  m
    }

    String SPAM_MESSAGE = "Your message was flagged as spam.";

    boolean probablySpam = false;
    String spamReason = "";

    String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer");
    request.getSession().removeAttribute("commentsFormReferer");
    if (originalReferer == null) {
        originalReferer = "none";
        // (the following does not support cookie-less browsing:)
        // probablySpam = true;
        // status = SPAM_MESSAGE;
    } else {
        String referer = request.getHeader("Referer");
        //Review how spam works?
        /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) {
        probablySpam=true;
        status = SPAM_MESSAGE ;
        spamReason = "The form was not submitted from the Contact Us or Corrections page.";
        }*/
    }

    String formType = vreq.getParameter("DeliveryType");
    List<String> deliverToArray = null;
    int recipientCount = 0;
    String deliveryfrom = null;

    // get Individuals that the User mayEditAs
    deliverToArray = getEmailsForAllUserAccounts(vreq);

    //Removed all form type stuff b/c recipients pre-configured
    recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();

    if (recipientCount == 0) {
        //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\"");
        throw new Error("To establish the Contact Us mail capability the system administrators must  "
                + "specify at least one email address in the current portal.");
    }

    // obtain passed in form data with a simple trim on the values
    String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception
    String webuseremail = vreq.getParameter("webuseremail");//.trim();
    String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify?
    //webusername = "hjk54";
    //webuseremail = "hjk54@cornell.edu";
    //comments = "following are comments";

    webusername = webusername.trim();
    deliveryfrom = webuseremail;
    comments = comments.trim();
    //Removed spam filtering code

    StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message
    String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix
    // from MyLibrary
    msgBuf.setLength(0);
    //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator);
    msgBuf.append("<html>" + lineSeparator);
    msgBuf.append("<head>" + lineSeparator);
    msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator);
    msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator);
    msgBuf.append("</head>" + lineSeparator);
    msgBuf.append("<body>" + lineSeparator);
    msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator);
    msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address "
            + request.getRemoteAddr() + "</h4>" + lineSeparator);

    //Don't need any 'likely viewing page' portion to be emailed out to the others

    msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator);
    if (comments == null || comments.equals("")) {
        msgBuf.append("<p>BLANK MESSAGE</p>");
    } else {
        msgBuf.append("<p>" + comments + "</p>");
    }
    msgBuf.append("</body>" + lineSeparator);
    msgBuf.append("</html>" + lineSeparator);

    String msgText = msgBuf.toString();

    Calendar cal = Calendar.getInstance();

    /* outFile.println("<hr/>");
     outFile.println();
     outFile.println("<p>"+cal.getTime()+"</p>");
     outFile.println();
     if (probablySpam) {
    outFile.println("<p>REJECTED - SPAM</p>");
    outFile.println("<p>"+spamReason+"</p>");
    outFile.println();
     }
     outFile.print( msgText );
     outFile.println();
     outFile.println();
     outFile.flush();
     // outFile.close();
    */

    Session s = FreemarkerEmailFactory.getEmailSession(vreq);
    //s.setDebug(true);
    try {
        // Construct the message
        MimeMessage msg = new MimeMessage(s);
        log.debug("trying to send message from servlet");

        // Set the from address
        msg.setFrom(new InternetAddress(webuseremail));

        // Set the recipient address

        if (recipientCount > 0) {
            InternetAddress[] address = new InternetAddress[recipientCount];
            for (int i = 0; i < recipientCount; i++) {
                address[i] = new InternetAddress(deliverToArray.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        // Set the subject and text
        msg.setSubject(deliveryfrom);

        // add the multipart to the message
        msg.setContent(msgText, "text/html");

        // set the Date: header
        msg.setSentDate(new Date());

        log.debug("sending from servlet");

        //if (!probablySpam)
        Transport.send(msg); // try to send the message via smtp - catch error exceptions

    } catch (AddressException e) {
        status = "Please supply a valid email address.";
        log.debug("Error - status is " + status);
    } catch (SendFailedException e) {
        status = "The system was unable to deliver your mail.  Please try again later.  [SEND FAILED]";
        log.error("Error - status is " + status);
    } catch (MessagingException e) {
        status = "The system was unable to deliver your mail.  Please try again later.  [MESSAGING]";
        log.error("Error - status is " + status, e);
    }

    //outFile.flush();
    //outFile.close();

    // Redirect to the appropriate confirmation page
    if (status == null && !probablySpam) {
        // message was sent successfully
        response.sendRedirect("test?bodyJsp=" + confirmpage);
    } else {
        // exception occurred
        response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status);
    }

}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification//from w  ww.  ja  v  a 2 s .  c o m
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

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

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

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

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

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}

From source file:org.georchestra.console.mailservice.Email.java

protected void sendMsg(String msg) throws AddressException, MessagingException {

    if (LOG.isDebugEnabled()) {
        LOG.debug("body: " + msg);
    }//from w w w.j av  a2s  .c om

    // Replace {publicUrl} token with the configured public URL
    msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl"));

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", smtpHost);
    session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString());

    final MimeMessage message = new MimeMessage(session);

    if (isValidEmailAddress(from)) {
        message.setFrom(new InternetAddress(from));
    }
    boolean validRecipients = false;
    for (String recipient : recipients) {
        if (isValidEmailAddress(recipient)) {
            validRecipients = true;
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
    }

    if (!validRecipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(from));
        message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding);
    } else {
        message.setSubject(subject, subjectEncoding);
    }

    if (msg != null) {
        /* See http://www.rgagnon.com/javadetails/java-0321.html */
        if ("true".equalsIgnoreCase(emailHtml)) {
            message.setContent(msg, "text/html; charset=" + bodyEncoding);
        } else {
            message.setContent(msg, "text/plain; charset=" + bodyEncoding);
        }
        LOG.debug(msg);
    }

    Transport.send(message);
    LOG.debug("email has been sent to:\n" + Arrays.toString(recipients));
}

From source file:mitm.application.djigzo.james.mailets.NotifyTest.java

@Test
public void testInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Notify mailet = new Notify();

    mailetConfig.setInitParameter("template", "encryption-notification.ftl");
    mailetConfig.setInitParameter("recipients", "originator");
    mailetConfig.setInitParameter("processor", "testProcessor");
    mailetConfig.setInitParameter("passThrough", "false");

    mailet.init(mailetConfig);//w w w  .j av a  2 s  .  com

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test\n", "text/plain");
    message.setHeader("From", "!@#$%^&*(");

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("recipient@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("sender@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertEquals(0, listener.getSenders().size());
    assertEquals(0, listener.getRecipients().size());
    assertEquals(0, listener.getStates().size());
    assertEquals(0, listener.getMessages().size());
    assertEquals(0, listener.getMails().size());

    assertNull(mail.getState());
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data// w  w w .j  av a2  s  .  co  m
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

private Result sendMail(MCPackageMail mcPackageMail) {
    try {/*from  w  w  w .  j a  va2 s .c  o  m*/
        Map<String, String> statusAction = new HashMap<>();
        statusAction.put("NEW", "released");
        statusAction.put("CANCEL", "withdrawn");
        statusAction.put("UPDATE", "updated");

        String html = mcPackageMail.getMail();

        ArrayList<String> to = new ArrayList<>();
        to.add(mcPackageMail.getDestination());

        String from = mcPackageMail.getSource();
        String host = Configuration.getInstance().getSmtpHost();
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.localhost", host);
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        for (String s : to) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
        }

        System.out.println("Destination: " + Arrays.asList(to).toString());

        message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", ""));
        message.setContent(html, "text/html");
        Transport.send(message);
        System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-"
                + mcPackageMail.getPackageVersion() + " was succesfully sent!");

    } catch (Exception ex) {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        result.setResultCode("1");
        result.setResultMessage(ex.getMessage());
    }

    return result;
}

From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java

/**
 * Send an email to the given email address with the given subject line,
 * using contents generated from the given template and parameters.
 *
 * @param templateName The name of the template used to generate the
 * contents of the email./*w w  w  . j  a v a 2s. com*/
 * @param subject The subject for the email being sent.
 * @param emailAddress Sends the email to this address.
 * @param params The template is merged with these parameters to generate
 * the content of the email.
 * @throws EmailException Thrown if there are any errors in generating
 * content from the template, composing the email, or sending the email.
 */
private void sendMessage(final String templateName, final String subject, final String emailAddress,
        final Map<String, Object> params) throws EmailException {
    Writer stringWriter = new StringWriter();
    try {
        Template template = this.configuration.getTemplate(templateName);
        template.process(params, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new EmailException(e);
    }

    String content = stringWriter.toString();
    MimeMessage message = new MimeMessage(this.session);
    try {
        InternetAddress fromEmailAddress = null;
        String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress();
        if (fromEmailAddressStr != null) {
            fromEmailAddress = new InternetAddress(fromEmailAddressStr);
        }
        if (fromEmailAddress == null) {
            fromEmailAddress = InternetAddress.getLocalAddress(this.session);
        }
        if (fromEmailAddress == null) {
            try {
                fromEmailAddress = new InternetAddress(
                        "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName());
            } catch (UnknownHostException ex) {
                fromEmailAddress = new InternetAddress("no-reply@localhost");
            }
        }
        message.setFrom(fromEmailAddress);
        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
        message.setSender(fromEmailAddress);
        Transport.send(message);
    } catch (MessagingException e) {
        LOGGER.error("Error sending the following email message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            message.writeTo(out);
            out.close();
        } catch (IOException | MessagingException ex) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
        LOGGER.error(out.toString());
        throw new EmailException(e);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Verifies the signature of the passed signed part*/
public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType,
        X509Certificate certificate) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    String signatureTransferEncoding = null;
    MimeMultipart checkPart = (MimeMultipart) signedPart.getContent();
    //it is sure that it is a signed part: set the type to multipart if the
    //parser has problems parsing it. Don't know why sometimes a parsing fails for
    //MimeBodyPart. This check looks if the parser is able to find more than one subpart
    if (checkPart.getCount() == 1) {
        MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType));
        MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null));
        possibleSignedMessage.setContent(multipart, multipart.getContentType());
        possibleSignedMessage.saveChanges();
        //overwrite the formerly found signed part
        signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage);
    }//from   ww w .j  av a2  s. com
    //get the content encoding of the signature
    MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent();
    //body part 1 is always the signature
    String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding");
    if (encodingHeader != null) {
        signatureTransferEncoding = encodingHeader[0];
    }
    return (helper.verify(signedPart, signatureTransferEncoding, certificate));
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

protected void generateMail(String destination, String copy, String title, String content)
        throws NamingException, MessagingException {

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(getJavaMailJndiName());

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false));
    if (!isBlank(copy)) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false));
    }//from  ww  w  .  ja v  a2s . c om

    msg.setSubject(title, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content, "text/html; charset=utf-8");

    Transport.send(msg);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java

private void sendMessage(Session s, String webuseremail, String webusername, String[] recipients,
        String deliveryfrom, String msgText) throws AddressException, SendFailedException, MessagingException {
    // Construct the message
    MimeMessage msg = new MimeMessage(s);
    //System.out.println("trying to send message from servlet");

    // Set the from address
    try {/*from www  . j av  a  2s.c om*/
        msg.setFrom(new InternetAddress(webuseremail, webusername));
    } catch (UnsupportedEncodingException e) {
        log.error("Can't set message sender with personal name " + webusername
                + " due to UnsupportedEncodingException");
        msg.setFrom(new InternetAddress(webuseremail));
    }

    // Set the recipient address
    InternetAddress[] address = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        address[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, address);

    // Set the subject and text
    msg.setSubject(deliveryfrom);

    // add the multipart to the message
    msg.setContent(msgText, "text/html");

    // set the Date: header
    msg.setSentDate(new Date());

    Transport.send(msg); // try to send the message via smtp - catch error exceptions

}