Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 *
 * @param addressTo//from  w w  w .  ja va 2 s .com
 * @param subject
 * @param message
 *
 */
private void send(InternetAddress[] addressTo, String subject, String message) {
    try {
        MimeMessage msg = new MimeMessage(createSession());
        msg.setFrom(new InternetAddress(USERNAME));
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
    } catch (Exception ex) {
        //logger.warn(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:davmail.smtp.TestSmtp.java

public void testSendSimpleMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test message";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body);//from   ww w  . j av a  2  s  . c  o  m
    sendAndCheckMessage(mimeMessage);
}

From source file:com.datatorrent.lib.io.SmtpOutputOperator.java

private void resetMessage() {
    if (!setupCalled) {
        return;/*from  w  w  w .  j  a  va2 s.  c  o m*/
    }
    try {
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        for (Map.Entry<String, String> entry : recipients.entrySet()) {
            RecipientType type = RecipientType.valueOf(entry.getKey().toUpperCase());
            Message.RecipientType recipientType;
            switch (type) {
            case TO:
                recipientType = Message.RecipientType.TO;
                break;
            case CC:
                recipientType = Message.RecipientType.CC;
                break;
            case BCC:
            default:
                recipientType = Message.RecipientType.BCC;
                break;
            }
            String[] addresses = entry.getValue().split(",");
            for (String address : addresses) {
                message.addRecipient(recipientType, new InternetAddress(address));
            }
        }
        message.setSubject(subject);
        LOG.debug("all recipients {}", Arrays.toString(message.getAllRecipients()));
    } catch (MessagingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.fiveamsolutions.nci.commons.util.MailUtils.java

/**
 * Send an email.//from   w  w w  .  j  av  a2s  .  c o m
 * @param u the recipient of the message
 * @param title the subject of the message
 * @param html the html content of the message
 * @param plainText the plain text content of the message
 * @throws MessagingException on error.
 */
public static void sendEmail(AbstractUser u, String title, String html, String plainText)
        throws MessagingException {
    if (!isMailEnabled()) {
        LOG.info("sending email to " + u.getEmail() + " with title " + title);
        LOG.info("plain text: " + plainText);
        LOG.info("html: " + html);
        return;
    }
    MimeMessage msg = new MimeMessage(getMailSession());
    msg.setFrom(new InternetAddress(getFromAddress()));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));
    msg.setSubject(title);
    Multipart mp = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(html, "text/html");
    mp.addBodyPart(bp);

    bp = new MimeBodyPart();
    bp.setContent(plainText, "text/plain");
    mp.addBodyPart(bp);

    msg.setContent(mp);

    Transport.send(msg);
}

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry/*  ww  w .j a  v  a 2  s.  c o  m*/
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;//from   www  .ja v  a  2s .  c o m
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }// w w  w  . j  a  va  2s  .  c om
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.esri.gpt.framework.mail.MailRequest.java

/**
 * Sends the E-Mail message./*from  w  w  w .j  a v a  2s  .c  o  m*/
 * @throws AddressException if an E-Mail address is invalid
 * @throws MessagingException if an exception occurs
 */
public void send() throws AddressException, MessagingException {

    // setup the mail server properties
    Properties props = new Properties();
    props.put("mail.smtp.host", getHost());
    if (getPort() > 0) {
        props.put("mail.smtp.port", "" + getPort());
    }

    // set up the message
    Session session = Session.getDefaultInstance(props, _authenticator);
    Message message = new MimeMessage(session);
    message.setSubject(getSubject());
    message.setContent(getBody(), getMimeType());
    message.setFrom(makeAddress(escapeHtml4(stripControls(getFromAddress()))));
    for (String sTo : getRecipients()) {
        message.addRecipient(Message.RecipientType.TO, makeAddress(sTo));
    }

    // send the message
    Transport.send(message);
}

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;//ww  w.j  a  va2s.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:mitm.common.mail.MailUtilsTest.java

@Test
public void testValidateMessageShouldFail() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();//from  w w w  .j  av  a 2s. c  o m

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}