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:com.mylab.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();/*from   w ww  .j  a v  a  2 s  .  c om*/
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(mimeMessage, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}

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

@Test
public void testRequestCertificateInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/* ww w.j  a va2s.  c o m*/

    MockMail mail = new MockMail();

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

    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(null);

    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
}

From source file:io.starter.datamodel.Sys.java

/**
 * /*w  ww  .  ja  va2 s.c  om*/
 * @param params
 * @throws Exception
 * 
 * 
 */
public static void sendEmail(String url, final User from, String toEmail, Map params, SqlSession session,
        CountDownLatch latch) throws Exception {

    final CountDownLatch ltc = latch;

    if (from == null) {
        throw new ServletException("Sys.sendEmail cannot have a null FROM User.");
    }
    String fromEmail = from.getEmail();
    final String fro = fromEmail;
    final String to = toEmail;
    final Map p = params;
    final String u = url;
    final SqlSession sr = session;

    // TODO: check message sender/recipient validity
    if (!checkEmailValidity(fromEmail)) {
        throw new RuntimeException(
                fromEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED");
    }
    // TODO: check mail server if it's a valid message
    if (!checkEmailValidity(toEmail)) {
        throw new RuntimeException(
                toEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED");
    }

    // message.setSubject("Testing Email From Starter.io");
    // Send the actual HTML message, as big as you like
    // fetch the content
    final String content = getText(u);

    new Thread(new Runnable() {
        @Override
        public void run() {
            // Sender's email ID needs to be mentioned
            // String sendAccount = "$EMAIL_USER_NAME$";

            // final String username = "$EMAIL_USER_NAME$", password =
            // "hum0rm3";

            // Assuming you are sending email from localhost
            // String host = "gator3083.hostgator.com";

            String sendAccount = "$EMAIL_USER_NAME$";
            final String username = "$EMAIL_USER_NAME$", password = "$EMAIL_USER_PASS$";

            // Assuming you are sending email from localhost
            String host = SystemConstants.EMAIL_SERVER;

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

            // Setup mail server
            props.setProperty("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.port", "587");

            // Get the default Session object.
            Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            try {
                // Create a default MimeMessage object.
                MimeMessage message = new MimeMessage(session);

                // Set From: header field of the header.
                message.setFrom(new InternetAddress(sendAccount));
                // Set To: header field of the header.
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

                message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendAccount));

                // Set Subject: header field
                Object o = p.get("MESSAGE_SUBJECT");
                message.setSubject(o.toString());

                String ctx = new String(content.toString());

                // TODO: String Rep on the params
                ctx = stringRep(ctx, p);

                message.setContent(ctx, "text/html; charset=utf-8");

                // message.setContent(new Multipart());
                // Send message
                Transport.send(message);

                Logger.log("Sending message to:" + to + " SUCCESS");
            } catch (MessagingException mex) {
                // mex.printStackTrace();
                Logger.log("Sending message to:" + to + " FAILED");
                Logger.error("Sys.sendEmail() failed to send message. Messaging Exception: " + mex.toString());
            }
            // log the data
            Syslog logEntry = new Syslog();

            logEntry.setDescription("OK [ email sent from: " + fro + " to: " + to + "]");

            logEntry.setUserId(from.getId());
            logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SEND_EMAIL);
            logEntry.setSourceId(from.getId()); // unknown
            logEntry.setSourceType(SystemConstants.TARGET_TYPE_USER);

            logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis()));
            SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
            SqlSession sesh = sqlSessionFactory.openSession(true);

            sesh.insert("io.starter.dao.SyslogMapper.insert", logEntry);
            sesh.commit();
            if (ltc != null)
                ltc.countDown(); // release the latch
        }
    }).start();

}

From source file:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Converts the message object to a mime message in order to prepare it to be sent.
 *
 * @param message// w ww. j  a  v a  2  s .c  om
 * @return MimeMessage
 */
public MimeMessage createMimeMessage(Message message) throws Exception {

    if (message.getRecipients() == null) {
        throw new MessageException("Message must contain at least one recipient");
    }

    // set the content-type to the default if it isn't defined in Message
    if (!StringUtils.hasText(message.getContentType())) {
        String contentType = Context.getAdministrationService().getGlobalProperty("mail.default_content_type");
        message.setContentType(StringUtils.hasText(contentType) ? contentType : "text/plain");
    }

    MimeMessage mimeMessage = new MimeMessage(session);

    // TODO Need to test the null case.  
    // Transport should use default mail.from value defined in properties.
    if (message.getSender() != null) {
        mimeMessage.setSender(new InternetAddress(message.getSender()));
    }

    mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(message.getRecipients(), false));
    mimeMessage.setSubject(message.getSubject());

    if (!message.hasAttachment()) {
        mimeMessage.setContent(message.getContent(), message.getContentType());
    } else {
        mimeMessage.setContent(createMultipart(message));
    }

    return mimeMessage;
}

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

@Test
public void testRequestCertificateNotAddUser() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailetConfig.setInitParameter("addUser", "false");

    mailet.init(mailetConfig);//from w w w  .  j  a v a2s.co  m

    MockMail mail = new MockMail();

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

    String from = "from@example.com";
    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

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

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*from   w  w  w  . java 2 s  . c o m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

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

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

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Mailet mailet = new BlackberrySMIMEAdapter();

    String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl"));

    autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template);

    mailetConfig.setInitParameter("log", "starting");
    /* use some dummy template because we must specify the default template */
    mailetConfig.setInitParameter("template", "sms.ftl");
    mailetConfig.setInitParameter("templateProperty", "pdfTemplate");

    mailet.init(mailetConfig);//  w w  w .  j  a  v  a 2 s  .c  o  m

    MockMail mail = new MockMail();

    mail.setState(Mail.DEFAULT);

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

    MimeBodyPart emptyPart = new MimeBodyPart();

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

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("123@EXAMPLE.com"));

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    assertEquals(message, mail.getMessage());

    try {
        MailUtils.validateMessage(message);

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

From source file:edu.cornell.mannlib.vitro.webapp.utils.MailUtil.java

public void sendMessage(String messageText, String subject, String from, String to, List<String> deliverToArray)
        throws IOException {

    Session s = FreemarkerEmailFactory.getEmailSession(req);

    try {//from  ww w.  ja v  a  2  s  .  c o m

        int recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();
        if (recipientCount == 0) {
            log.error("To establish the Contact Us mail capability the system administrators must  "
                    + "specify at least one email address in the current portal.");
        }

        MimeMessage msg = new MimeMessage(s);
        // Set the from address
        msg.setFrom(new InternetAddress(from));

        // 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(subject);

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

        // set the Date: header
        msg.setSentDate(new Date());
        Transport.send(msg); // try to send the message via smtp - catch error exceptions
    } catch (Exception ex) {
        log.error("Exception sending message :" + ex.getMessage(), ex);
    }
}

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

public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date,
        Date checkout_date) {//from  w  w  w.j  av  a  2 s. c  om
    Integer guestID = 0, guestCount;
    String room_selected = guestDTO.getRoom_no_selected();
    Guest guestObject = new Guest();

    try {
        org.apache.commons.beanutils.BeanUtils.copyProperties(guestObject, guestDTO);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    //check email id if exist
    guestID = guestDAO.checkGuestExist(guestDTO.getGuest_email(), guestDTO.getLicense_no());
    System.out.println("guestID: " + guestID);
    //if email id, license exist
    if (!(guestID == 0)) {
        System.out.println("value = ");
        //update details
        guestCount = guestDAO.updateUserDetails(guestID, guestDTO.getGuest_name(), guestDTO.getStreet(),
                guestDTO.getCity(), guestDTO.getState(), guestDTO.getZip());
        if (guestCount != 0)
            guestObject = guestDAO.getGuestRecord(guestID);
    } else {
        guestObject = guestDAO.save(guestObject);
    }

    String randomDate = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis());

    UUID id = UUID.randomUUID();
    String token_no = String.valueOf(id);
    //System.out.println(sensor_id);

    // String token_no = guestObject.getLicense_no() + guestObject.getGuest_id()+randomDate;

    java.util.Date todayUtilDate = Calendar.getInstance().getTime();//2015-12-05
    java.sql.Date todaySqlDate = new java.sql.Date(todayUtilDate.getTime());

    Reservation reservationObject = new Reservation();
    //        reservationObject.setReservation_id(0);
    reservationObject.setGuest_id(guestObject.getGuest_id());
    reservationObject.setReservation_token(token_no);
    reservationObject.setReservation_date(todaySqlDate);
    reservationObject.setReservation_status(ReservationStatus.R);
    reservationObject = reservationDAO.save(reservationObject);
    // Integer reservation_id = reservationObject.getReservation_id();

    String[] resultStringArray = guestDTO.getRoom_no_selected().split(",");
    ArrayList<Integer> arrRooms = new ArrayList<Integer>();
    for (String str : resultStringArray) {
        arrRooms.add(Integer.parseInt(str));
        CheckinRoomMapping checkinRoomMappingObject = new CheckinRoomMapping();
        checkinRoomMappingObject.setReservation(reservationObject);
        checkinRoomMappingObject.setRoom_no(Integer.parseInt(str));
        checkinRoomMappingObject.setCheckin_date(checkin_date);
        checkinRoomMappingObject.setCheckout_date(checkout_date);
        checkinRoomMappingObject.setGuest_count(0);
        checkinRoomMappingObject.setMappingId(0);
        checkinRoomMappingDAO.save(checkinRoomMappingObject);
    }
    //add email code start here

    final String from = "express.minihotel@gmail.com";
    String to = guestObject.getGuest_email();
    String body = "Hello " + guestObject.getGuest_name()
            + ", <br/><br></br>Your reservation has been confirmed.Your reservation ID is <font color='red'><b>"
            + token_no
            + "</b></font>.</br>Please bring the Driving License for verification at the time of Check In.</br><br></br>"
            + "<b>Note:</b>If you want to cancel the reservation, "
            + "please <a href=\'http://52.53.255.195:8080/CmpE275Team07Fall2015TermProject/v1/cancelReservation?reservation_token="
            + token_no + "\'>Click Here</a><br></br>--<i>Express Hotel</i>";
    String subject = "Express Hotel Reservation Confirmation <" + token_no + ">";

    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 code end here

    return token_no;
}

From source file:de.tuttas.servlets.MailSender.java

private void transmitMail(MailObject mo) throws MessagingException {

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Config.getInstance().user, Config.getInstance().pass);
        }/* w w  w  . java 2 s  .co m*/
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mo.getFrom()));
    InternetAddress[] toAddresses = mo.getRecipient();
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    InternetAddress[] bccAdresses = mo.getBcc();
    InternetAddress[] ccAdresses = mo.getCC();

    if (bccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.BCC, bccAdresses);
    if (ccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.CC, ccAdresses);
    msg.setSubject(mo.getSubject(), "UTF-8");

    msg.setSentDate(new Date());
    msg.setContent(mo.getContent(), "text/plain; charset=UTF-8");
    // sends the e-mail
    // TODO Kommentar entfernen
    Transport.send(msg);
}