Example usage for javax.mail.internet InternetAddress parse

List of usage examples for javax.mail.internet InternetAddress parse

Introduction

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

Prototype

public static InternetAddress[] parse(String addresslist) throws AddressException 

Source Link

Document

Parse the given comma separated sequence of addresses into InternetAddress objects.

Usage

From source file:Model.DAO.java

public void sendEmail(int id, String status) {
    SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
    Properties props = new Properties();
    /** Parmetros de conexo com servidor Gmail */
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("seuemail@gmail.com", "suasenha");
        }/*from ww w .j  a va  2 s .  co m*/
    });

    /** Ativa Debug para sesso */

    try {
        PreparedStatement stmt = this.conn
                .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?");
        stmt.setInt(1, id);
        ResultSet rs = stmt.executeQuery();
        rs.next();
        String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0];
        String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1];
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente

        Address[] toUser = InternetAddress //Destinatrio(s)
                .parse(rs.getString("email"));

        message.setRecipients(Message.RecipientType.TO, toUser);
        message.setSubject("Status Reserva");//Assunto
        message.setText("Email de alterao do status da resreva no dia " + date + " s " + time
                + " horas para " + status);
        /**Mtodo para enviar a mensagem criada*/
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (SQLException ex) {
        Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

public void init() {
    PropertyCheck.mandatory(this, "imapConfigMountPoints", imapConfigMountPoints);
    PropertyCheck.mandatory(this, "ignoreExtractionFoldersBeans", ignoreExtractionFoldersBeans);
    PropertyCheck.mandatory(this, "imapHome", imapHomeConfigBean);

    PropertyCheck.mandatory(this, "fileFolderService", fileFolderService);
    PropertyCheck.mandatory(this, "nodeService", nodeService);
    PropertyCheck.mandatory(this, "permissionService", permissionService);
    PropertyCheck.mandatory(this, "serviceRegistry", serviceRegistry);
    PropertyCheck.mandatory(this, "defaultFromAddress", defaultFromAddress);
    PropertyCheck.mandatory(this, "defaultToAddress", defaultToAddress);
    PropertyCheck.mandatory(this, "repositoryTemplatePath", repositoryTemplatePath);
    PropertyCheck.mandatory(this, "policyBehaviourFilter", policyBehaviourFilter);
    PropertyCheck.mandatory(this, "namespaceService", namespaceService);
    PropertyCheck.mandatory(this, "searchService", getSearchService());
    this.folderCache = new MaxSizeMap<Pair<String, String>, FolderStatus>(folderCacheSize, false);

    // be sure that a default e-mail is correct
    try {/*from   www. j a  v  a 2s . c o m*/
        InternetAddress.parse(defaultFromAddress);
    } catch (AddressException ex) {
        throw new AlfrescoRuntimeException(ERROR_CANNOT_PARSE_DEFAULT_EMAIL,
                new Object[] { defaultFromAddress });
    }

    try {
        InternetAddress.parse(defaultToAddress);
    } catch (AddressException ex) {
        throw new AlfrescoRuntimeException(ERROR_CANNOT_PARSE_DEFAULT_EMAIL, new Object[] { defaultToAddress });
    }
}

From source file:org.xerela.server.birt.ReportJob.java

private void setupEmail(JobExecutionContext executionContext, String emailTo, String emailCc, Email email)
        throws AddressException, EmailException {
    InternetAddress[] toAddrs = InternetAddress.parse(emailTo);
    email.setTo(Arrays.asList(toAddrs));

    if (emailCc != null && emailCc.trim().length() > 0) {
        InternetAddress[] ccAddrs = InternetAddress.parse(emailCc);
        email.setCc(Arrays.asList(ccAddrs));
    }//  w w  w.ja  va2  s.com

    email.setCharset("utf-8"); //$NON-NLS-1$
    email.setHostName(System.getProperty(MAIL_HOST_PROP, "mail")); //$NON-NLS-1$
    String authUser = System.getProperty(MAIL_AUTH_USER_PROP);
    if (authUser != null) {
        email.setAuthentication(authUser, System.getProperty(MAIL_AUTH_PASSWORD_PROP));
    }
    email.setFrom(System.getProperty(MAIL_FROM_PROP), System.getProperty(MAIL_FROM_NAME_PROP));
    email.setSubject(
            Messages.bind(Messages.ReportJob_emailSubject, executionContext.getJobDetail().getFullName()));
    email.addHeader("X-Mailer", "Xerela Mailer"); //$NON-NLS-1$ //$NON-NLS-2$
    email.setDebug(Boolean.getBoolean("org.xerela.mail.debug")); //$NON-NLS-1$
}

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

public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name,
        Double discountDouble) {//  w w  w  .  j  av a 2s  . c  o 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:checkwebsite.Mainframe.java

/**
 *
 * @param email// w w  w .  j  av  a 2 s  . co m
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

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

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

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

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

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

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Encode UTF strings into mail addresses.
 *
 * @param string DOCUMENT ME!/*w ww.  j av a2  s .c o m*/
 * @param charset DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static InternetAddress[] encodeAddresses(String string, String charset) throws MessagingException {
    if (string == null) {
        return null;
    }

    // parse the string into the internet addresses
    // NOTE: these will NOT be character encoded
    InternetAddress[] xaddresses = InternetAddress.parse(string);

    // now encode each to the given character set
    if (charset != null) {
        for (int xindex = 0; xindex < xaddresses.length; xindex++) {
            String xpersonal = xaddresses[xindex].getPersonal();

            try {
                if (xpersonal != null) {
                    if (charset != null) {
                        xaddresses[xindex].setPersonal(xpersonal, charset);
                    } else {
                        xaddresses[xindex].setPersonal(xpersonal, "ISO-8859-1");
                    }
                }
            } catch (UnsupportedEncodingException xex) {
                throw new MessagingException(xex.toString());
            }
        }
    }

    return xaddresses;
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

/**
 * @param context the current context//  www  .j  a  va  2 s  . c  om
 * @param flowFile the current flow file
 * @param propertyDescriptor the property to evaluate
 * @return an InternetAddress[] parsed from the supplied property
 * @throws AddressException if the property cannot be parsed to a valid InternetAddress[]
 */
private InternetAddress[] toInetAddresses(final ProcessContext context, final FlowFile flowFile,
        PropertyDescriptor propertyDescriptor) throws AddressException {
    InternetAddress[] parse;
    String value = context.getProperty(propertyDescriptor).evaluateAttributeExpressions(flowFile).getValue();
    if (value == null || value.isEmpty()) {
        if (propertyDescriptor.isRequired()) {
            final String exceptionMsg = "Required property '" + propertyDescriptor.getDisplayName()
                    + "' evaluates to an empty string.";
            throw new AddressException(exceptionMsg);
        } else {
            parse = new InternetAddress[0];
        }
    } else {
        try {
            parse = InternetAddress.parse(value);
        } catch (AddressException e) {
            final String exceptionMsg = "Unable to parse a valid address for property '"
                    + propertyDescriptor.getDisplayName() + "' with value '" + value + "'";
            throw new AddressException(exceptionMsg);
        }
    }
    return parse;
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

private InternetAddress[] createAddresses(Element addressElement)
        throws AddressException, UnsupportedEncodingException {
    final String email = addressElement.element("email").getStringValue();
    final Element nameElement = addressElement.element("name");
    // If only the <email> element is specified, allow for comma-separated addresses
    return nameElement == null ? InternetAddress.parse(email)
            : new InternetAddress[] { new InternetAddress(email, nameElement.getStringValue()) };
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!// w  ww .j av  a  2s.  com
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

            email.send();
        }
    } catch (Exception e) {
    } finally {
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected InternetAddress[] getRecipients(long messageId, RecipientType recipientType) throws PortalException {

    try {// w w  w  .  j  ava2  s .  com
        com.liferay.mail.model.Message message = MessageLocalServiceUtil.getMessage(messageId);

        if (recipientType.equals(RecipientType.TO)) {
            return InternetAddress.parse(message.getTo());
        } else if (recipientType.equals(RecipientType.CC)) {
            return InternetAddress.parse(message.getCc());
        } else if (recipientType.equals(RecipientType.BCC)) {
            return InternetAddress.parse(message.getBcc());
        } else {
            throw new IllegalArgumentException("Invalid recipient type " + recipientType);
        }
    } catch (AddressException ae) {
        throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, ae);
    }
}