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.zotoh.crypto.CryptoUte.java

/**
 * @param user//  www. j  av  a  2s .c  o  m
 * @param pwd
 * @return
 */
public static MimeMessage newMimeMsg(String user, String pwd) {
    return new MimeMessage(newSession(user, pwd));
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {/*from   ww w  . j  a va2 s.  co m*/
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:com.bia.monitor.service.EmailService.java

/**
 *
 * @param addressTo/* ww w  . j a v  a  2 s . com*/
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    logger.info("sending email.. " + addressTo);
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    InternetAddress[] bcc1 = getBCC();
    msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void trialCreated(String subject, String fromUser, String fromName, String toUser,
        InternetAddress[] toCC) {/*from  ww  w. j a va2s.com*/
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", "http://www.uengine.io/my/license");

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/trial-created.vm", "UTF-8",
            model);

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @return
 */
public static MimeMessage newMimeMsg() {
    return new MimeMessage(newSession());
}

From source file:mupomat.view.PodrskaLozinka.java

private void posaljiEmail() {

    final String username = "mupomat@gmail.com";
    final String password = "lesnibokysr187";

    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() {
        @Override/*from   www.j av  a  2  s. c  o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("mupomat@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtEmail.getText().trim()));
        message.setSubject("MUPomat podrka");

        message.setText("Nova lozinka: " + generiranaLozinka
                + "\nMolimo Vas da nakon prijave promjenite lozinku radi sigurnosti.\nHvala.");

        Transport.send(message);
        this.dispose();
        JOptionPane.showMessageDialog(rootPane, "Lozinka je uspjeno poslana na Vau e-mail adresu!",
                "MUPomat: Podrka", JOptionPane.INFORMATION_MESSAGE);

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

}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder/*from   w w  w . j  a  v  a 2  s .  co  m*/
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

From source file:com.meg7.emailer.EmailerManager.java

private Message createMessage(List<String> emails, String fromEmail, String fromName, String subject,
        String text, Session session) throws MessagingException, UnsupportedEncodingException {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(fromEmail, fromName));
    for (String email : emails) {
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email, email));
    }// w  ww  .  j a  v a 2  s . c  o m
    message.setSubject(subject);
    message.setText(text);
    return message;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static MimeMessageHelper createEmailMessage(String from, String to)
        throws AddressException, MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    for (String recipient : to.split(";")) {
        email.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }//from www . ja v  a2  s  .  c o  m

    return new MimeMessageHelper(email);
}

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

public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date,
        Date checkout_date) {/*w w w .  ja  v a 2s .c  o m*/
    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;
}