Example usage for javax.mail.internet MimeMessage setSubject

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

Introduction

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

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

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

@Override
public void serviceMail(Mail mail) {
    try {//from   w w w.  j a  v  a2 s  .c  om
        MimeMessage message = mail.getMessage();

        String currentSubject = message.getSubject();

        if (currentSubject != null) {
            String[] filter = getFilter(mail);

            if (filter != null) {
                Pattern pattern = patternCache.getPattern(StringUtils.defaultString(filter[0]));

                if (pattern != null) {
                    String newSubject = pattern.matcher(currentSubject)
                            .replaceAll(StringUtils.defaultString(filter[1]));

                    logger.debug("Currrent subject: {}, new subject: {}", currentSubject, newSubject);

                    message.setSubject(newSubject);
                }
            }
        } else {
            logger.debug("Subject is null");
        }
    } catch (MessagingException e) {
        logger.error("Error adding text to subject", e);
    }
}

From source file:org.tsm.concharto.web.feedback.FeedbackController.java

public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm,
        HttpServletRequest request) {//  ww w . j ava 2  s  .  co m

    //prepare the user info
    String requestInfo = getBrowserInfo(request);

    StringBuffer messageText = new StringBuffer(feedbackForm.getBody())
            .append("\n\n=============================================================\n").append(requestInfo);

    InternetAddress from = new InternetAddress();
    from.setAddress(feedbackForm.getEmail());
    InternetAddress to = new InternetAddress();
    to.setAddress(sendFeedbackToAddress);
    try {
        from.setPersonal(feedbackForm.getName());
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(FEEDBACK_SUBJECT + feedbackForm.getSubject());
        message.setText(messageText.toString());
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

From source file:com.project.implementation.ReservationImplementation.java

public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name,
        Double discountDouble) {/* www  .  ja v a  2 s. co  m*/

    //check if service agent exist
    List<User> userName = userDAO.verifyUserByUserName(user_name);
    Integer user_id = userName.get(0).getUser_id();
    System.out.println("user_id: " + user_id);
    String userNameString = userName.get(0).getUser_name().toString();
    System.out.println("userNameString: " + userNameString);

    ArrayList<HashMap<String, String>> billList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> billHash = new HashMap<String, String>();

    if (user_name.equals(userNameString)) {
        //fetch reservation id
        List<Reservation> reservRecords = reservationDAO.find(reservation_token);
        Integer reservation_id = reservRecords.get(0).getReservation_id();
        System.out.println("reservation_id: " + reservation_id);
        Integer guest_id = reservRecords.get(0).getGuest_id();
        System.out.println("guest_id:: " + guest_id);
        List<Guest> emailRecord = guestDAO.findGuestEmailId(reservRecords.get(0).getGuest_id());
        String guestEmailID = emailRecord.get(0).getGuest_email();
        String guestName = emailRecord.get(0).getGuest_name();
        System.out.println("emailRecord: " + guestEmailID);
        System.out.println("guestName: " + guestName);
        System.out.println(reservRecords.size());

        System.out.println(reservRecords.get(0).getReservation_id());
        Integer s = reservRecords.get(0).getReservation_id();
        System.out.println("integer value: " + s);
        //Integer reservation_id = reservRecords.get(0).getReservation_id();

        //fetch checkin mapping table data
        ReservationDTO reservDTO = new ReservationDTO();
        reservDTO.setReservation_id(reservRecords.get(0).getReservation_id());
        List<CheckinRoomMapping> checkinMappingRecords = checkinRoomMappingDAO.findMappingForBilling(reservDTO);
        Date checkin_date = checkinMappingRecords.get(0).getCheckin_date();
        Date checkout_date = checkinMappingRecords.get(0).getCheckout_date();

        long daysStay = ((checkout_date.getTime() - checkin_date.getTime()) / MILLISECONDS_IN_DAY) + 1;//
        System.out.println("daysStay: " + daysStay);
        String noOfDaysStayed = String.valueOf(daysStay);//
        System.out.println("noOfDaysStayed: " + noOfDaysStayed);
        Double totalBill = 0.0;
        ArrayList<HashMap<String, String>> mailContent = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < checkinMappingRecords.size(); i++) {
            System.out.println("Room(" + i + ") : " + checkinMappingRecords.get(i).getRoom_no());

            Integer room_no = checkinMappingRecords.get(i).getRoom_no();
            String roomNoInString = String.valueOf(room_no);//
            System.out.println("roomNoInString: " + roomNoInString);
            RoomDTO roomDTO = new RoomDTO();
            roomDTO.setRoom_no(room_no);

            Enum<RoomType> roomType = roomDAO.findRoomType(roomDTO);
            String type = roomType.toString();//
            if (type.equalsIgnoreCase("K"))
                type = "King";
            if (type.equalsIgnoreCase("Q"))
                type = "Queen";
            if (type.equalsIgnoreCase("SK"))
                type = "Smoking - King";
            if (type.equalsIgnoreCase("SQ"))
                type = "Smoking - Queen";
            System.out.println("room type: " + type);

            //Fetch price by room type
            Double roomPrice = roomPriceDAO.getRoomPrice(roomType);//
            System.out.println("roomPrice:::" + roomPrice);
            String roomPriceString = String.valueOf(roomPrice);
            System.out.println("roomPriceString: " + roomPriceString);
            Double billPerRoom = roomPrice * daysStay;//
            String billPerRoomString = String.valueOf(billPerRoom);
            System.out.println("billPerRoomString:" + billPerRoomString);
            totalBill = totalBill + billPerRoom;

            //set hash map
            HashMap<String, String> mailBody = new HashMap<String, String>();
            mailBody.put("Room_Number", roomNoInString);
            mailBody.put("Room_Type", type);
            mailBody.put("Room_Price", roomPriceString);
            mailBody.put("NoOfDays", noOfDaysStayed);
            mailBody.put("BillPerRoom", billPerRoomString);

            mailContent.add(mailBody);
            //end hash map

            System.out.println("-------");
        }
        System.out.println("totalBill::" + totalBill);
        String templateForEmailBody = "";
        for (HashMap<String, String> h : mailContent) {
            System.out.println("room_numer" + h.get("Room_Number"));
            templateForEmailBody = templateForEmailBody + "<tr><td>" + h.get("Room_Number") + "</td><td>"
                    + h.get("Room_Type") + "</td><td>" + h.get("Room_Price") + "</td><td>" + h.get("NoOfDays")
                    + "</td><td>" + h.get("BillPerRoom") + "</td><tr><br>";

        }
        System.out.println("templateForEmailBody" + templateForEmailBody);
        Integer bill_no = guest_id;
        String bill_no_String = String.valueOf(bill_no);
        System.out.println("discount" + discountDouble);
        //String bill_no_String = String.valueOf(discountDouble);

        Double totalDiscount = (discountDouble / 100) * totalBill;
        String totalDiscountString = String.valueOf(totalDiscount);

        Double amountPayable = totalBill - totalDiscount;
        String amountPayableString = String.valueOf(amountPayable);

        //ReservationDTO res = new ReservationDTO();
        BillingDTO billingDTO = new BillingDTO();
        billingDTO.setBill_no(bill_no);
        billingDTO.setReservation_id(reservation_id);
        billingDTO.setUser_id(user_id);
        billingDTO.setDiscount(totalDiscount);
        billingDTO.setAmount(amountPayable);

        Reservation resObj = new Reservation();
        resObj.setReservation_id(reservation_id);

        User userObj = new User();
        userObj.setUser_id(user_id);

        Billing billObject = new Billing();
        billObject.setBill_no(bill_no);
        billObject.setReservation(resObj);
        billObject.setUser(userObj);
        billObject.setDiscount(totalDiscount);
        billObject.setAmount(amountPayable);

        //            try {
        //                org.apache.commons.beanutils.BeanUtils.copyProperties(billObject, billingDTO);
        //            } catch (IllegalAccessException e) {
        //                e.printStackTrace();
        //            } catch (InvocationTargetException e) {
        //                e.printStackTrace();
        //            }

        Integer billID = billingDAO.insertBillData(billObject);
        System.out.println("Bill id after Insert: " + billID);

        if (billID != null) {
            //email

            final String from = "express.minihotel@gmail.com";
            String to = guestEmailID;
            String body = "Hello " + guestName + ",<br><br>You bill details are as follows:<br>"
                    + "<table border='1' style=\"border-collapse: collapse;\"><tr>"
                    + "<td><b>Room Number</b></td>" + "<td><b>Room Type</b></td>"
                    + "<td><b>Price per day ($)</b></td>" + "<td><b>Duration of Stay (days)</b></td>"
                    + "<td><b>Bill for Room ($)</b></td></tr>" + templateForEmailBody
                    + "</table><br>Net Bill: $" + totalBill + "<br><br>" + "Discount: $" + totalDiscountString
                    + "<br></br>" + "<br/><b>Total Bill Paid($): <font color='red'>" + amountPayable
                    + "</font></b><br></br><br></br>Thank You for choosing Express Hotel.<br/><br/><i>--Express Hotel</i>";

            String subject = "Express Hotel - Bill Receipt (Receipt No : " + bill_no_String + ")";
            final String password = "Minihotel@2015";
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
            Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, password);
                }
            });
            try {
                MimeMessage email = new MimeMessage(session);
                email.setFrom(new InternetAddress(from));
                email.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
                email.setSubject(subject);
                email.setContent(body, "text/html");
                Transport.send(email);

            } catch (MessagingException e) {

                throw new RuntimeException(e);

            }

            //email
            billHash.put("bill_amount", amountPayableString);
            billHash.put("bill_body", body);
            billList.add(billHash);
            //return billList;
        }
    } else {
        //username doesnot exist
        billHash.put("bill_amount", "User does not exist");
        billList.add(billHash);
        //return billList;
    }

    return billList;

}

From source file:org.apache.james.James.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce condition
 *
 * @return the bounce mail/*w  ww.  ja  v a  2s  .c o m*/
 *
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    //This sends a message to the james component that is a bounce of the sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection recipients = new HashSet();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress)
        throws MessagingException {

    MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart();

    // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview)
    MimeMultipart cover = new MimeMultipart("alternative");
    htmlAndPlainTextAlternativeBody.setContent(cover);
    BodyPart textHtmlBodyPart = new MimeBodyPart();
    String textHtmlBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".html.ftl");
    textHtmlBodyPart.setContent(textHtmlBody, "text/html");
    cover.addBodyPart(textHtmlBodyPart);

    BodyPart textPlainBodyPart = new MimeBodyPart();
    cover.addBodyPart(textPlainBodyPart);
    String textPlainBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".txt.ftl");
    textPlainBodyPart.setContent(textPlainBody, "text/plain");

    MimeMultipart content = new MimeMultipart("related");
    content.addBodyPart(htmlAndPlainTextAlternativeBody);

    // ATTACHMENTS
    for (BodyPart bodyPart : attachments) {
        content.addBodyPart(bodyPart);//from   ww w.  j  av a 2s  .  co m
    }

    MimeMessage msg = new MimeMessage(mailSession);

    msg.setFrom(mailFrom);
    msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
    msg.addRecipient(javax.mail.Message.RecipientType.CC, mailFrom);

    String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials";

    msg.setSubject(subject);
    msg.setContent(content);

    mailTransport.sendMessage(msg, msg.getAllRecipients());
}

From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java

public void sendEmail(EmailRecipient[] addresses, String subject, String[] body, String[] htmlBody,
        Integer priority) {//from w w  w.ja  v  a  2  s .  c  o m
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    final StopWatch watch = new StopWatch();

    try {
        InternetAddress from = getFromAddress();
        if (from == null) {
            mimeMessage.setFrom();
        } else {
            mimeMessage.setFrom(from);
        }

        // HHQ-5708
        // remove any possible new line from the subject
        // the subject can be render form 'subject.gsp' file
        mimeMessage.setSubject(subject.replace("\r", "").replace("\n", ""));

        // If priority not null, set it in body 
        if (priority != null) {
            switch (priority.intValue()) {
            case EventConstants.PRIORITY_HIGH:
                mimeMessage.addHeader("X-Priority", "1");
                break;
            case EventConstants.PRIORITY_MEDIUM:
                mimeMessage.addHeader("X-Priority", "2");
                break;
            default:
                break;
            }
        }

        // Send to each recipient individually (for D.B. SMS)
        for (int i = 0; i < addresses.length; i++) {
            mimeMessage.setRecipient(Message.RecipientType.TO, addresses[i].getAddress());

            if (addresses[i].useHtml()) {
                mimeMessage.setContent(htmlBody[i], "text/html; charset=UTF-8");
                if (log.isDebugEnabled()) {
                    log.debug("Sending HTML Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + htmlBody[i]);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Sending Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + body[i]);
                }
                mimeMessage.setContent(body[i], "text/plain; charset=UTF-8");
            }

            mailSender.send(mimeMessage);
        }
    } catch (MessagingException e) {
        log.error("MessagingException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", e);
    } catch (MailException me) {
        log.error("MailException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", me);
    } catch (Exception ex) {
        log.error(
                "Error in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]",
                ex);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Sending email using mailServer=" + mailSession.getProperties() + " took "
                    + watch.getElapsed() + " ms.");
        }
        if (watch.getElapsed() >= mailSmtpConnectiontimeout || (watch.getElapsed() >= mailSmtpTimeout)) {
            log.warn("Sending email using mailServer=" + mailSmtpHost + " took " + watch.getElapsed()
                    + " ms.  Please check with your mail administrator.");
        }
    }
}

From source file:fsi_admin.JSmtpConn.java

private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY,
        StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart,
        MimeMultipart multipart) {/*from  ww  w  .  ja  v a  2 s  . c  o  m*/
    // Create a message with the specified information. 
    try {
        mmsg.setFrom(new InternetAddress(FROM));
        mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        mmsg.setSubject(SUBJECT);
        messagebodypart.setContent(BODY, MIMETYPE);
        multipart.addBodyPart(messagebodypart);
        return true;
    } catch (AddressException e) {
        e.printStackTrace();
        msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage());
        return false;
    } catch (MessagingException e) {
        e.printStackTrace();
        msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage());
        return false;
    }
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * //from ww w  . java 2  s  . c o  m
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }/*  w ww  .  j av a 2s. co m*/
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*w ww  .  j a  va2  s. c  o  m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session session = Session.getInstance(props, null);

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

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

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

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

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}