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:info.raack.appliancedetection.common.email.SMTPEmailSender.java

public void sendGeneralEmail(String recipientEmail, String subject, String body) {
    Session session = Session.getDefaultInstance(emailProperties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from w ww .j a va2  s .  c  o m*/
    });

    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject(subject + (!environment.equals("prod") ? " [" + environment + "]" : ""));
        message.setText(body);
    } catch (Exception e) {
        throw new RuntimeException("Could not create message", e);
    }

    emailQueue.add(message);
}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override//w ww . j av a 2 s .  c  om
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

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

@Async
public void trialCreated(String subject, String fromUser, String fromName, String toUser,
        InternetAddress[] toCC) {/*from www . j  a  v  a 2s  . c  o m*/
    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: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 w w w . j  a  v a2 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.project.implementation.ReservationImplementation.java

public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date,
        Date checkout_date) {//ww  w  .  j a v  a2  s . 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;
}

From source file:org.exoplatform.answer.webui.FAQUtils.java

public static InternetAddress[] getInternetAddress(String addressList) throws Exception {
    if (isFieldEmpty(addressList))
        return new InternetAddress[1];
    try {//from  ww w  .  ja v  a  2s  .c  o m
        return InternetAddress.parse(addressList);
    } catch (Exception e) {
        return new InternetAddress[1];
    }
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * public method to send mail parameter is map with emailType, user
 *
 * @param mapConfigEmail//from   w  w w . j a  v a 2  s.com
 * @throws MessagingException
 */
@Async
public void sendEmail(Map<String, Object> mapConfigEmail) throws MessagingException {

    User user = (User) mapConfigEmail.get("user");
    String emailType = (String) mapConfigEmail.get("emailType");

    logger.info("start email configuration for " + emailType + " to : " + user.getEmail());
    logger.debug("EmailUtils : User " + user.toString());

    String body = null;
    try {
        mapConfigEmail = this.initEmailConfig(mapConfigEmail);
        mapConfigEmail = this.defineEmailType(mapConfigEmail);
        body = (String) mapConfigEmail.get("body");

        MimeMessage message = (MimeMessage) mapConfigEmail.get("message");

        // For Spring vagrant profil, we redirect all emails
        // If value is not set, we use the classic configuration
        if (applicationContext.getEnvironment().acceptsProfiles("vagrant")
                && emailForceRedirect.trim().length() > 0) {
            message.setRecipients(Message.RecipientType.TO, emailForceRedirect);
        } else {
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail()));
        }

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

        Transport.send(message);

    } catch (MessagingException e) {
        logger.error("Error sendEmail method - " + e);
        e.printStackTrace();
    }
    logger.info("Email of " + emailType + " send to " + user.getEmail());

}

From source file:com.waveerp.sendMail.java

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

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

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

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

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

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//from ww w. jav  a 2s  .com
    });

    try {

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

        Transport.send(message);

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

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

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

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

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

}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Send the given message over the Mail transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error/*from  ww w .ja v a 2 s.  c o  m*/
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    MailOutTransportInfo mailOutInfo = null;

    if (targetAddress != null) {
        if (targetAddress.startsWith(MailConstants.TRANSPORT_NAME)) {
            targetAddress = targetAddress.substring(MailConstants.TRANSPORT_NAME.length() + 1);
        }

        if (msgCtx.getReplyTo() != null
                && !AddressingConstants.Final.WSA_NONE_URI.equals(msgCtx.getReplyTo().getAddress())
                && !AddressingConstants.Final.WSA_ANONYMOUS_URL.equals(msgCtx.getReplyTo().getAddress())) {

            String replyTo = msgCtx.getReplyTo().getAddress();
            if (replyTo.startsWith(MailConstants.TRANSPORT_NAME)) {
                replyTo = replyTo.substring(MailConstants.TRANSPORT_NAME.length() + 1);
            }
            try {
                mailOutInfo = new MailOutTransportInfo(new InternetAddress(replyTo));
            } catch (AddressException e) {
                handleException("Invalid reply address/es : " + replyTo, e);
            }
        } else {
            mailOutInfo = new MailOutTransportInfo(smtpFromAddress);
        }

        try {
            mailOutInfo.setTargetAddresses(InternetAddress.parse(targetAddress));
        } catch (AddressException e) {
            handleException("Invalid target address/es : " + targetAddress, e);
        }
    } else if (outTransportInfo != null && outTransportInfo instanceof MailOutTransportInfo) {
        mailOutInfo = (MailOutTransportInfo) outTransportInfo;
    }

    if (mailOutInfo != null) {
        try {
            String messageID = sendMail(mailOutInfo, msgCtx);
            // this is important in axis2 client side if the mail transport uses anonymous addressing
            // the sender have to wait util the response comes.
            if (!msgCtx.getOptions().isUseSeparateListener() && !msgCtx.isServerSide()) {
                waitForReply(msgCtx, messageID);
            }
        } catch (MessagingException e) {
            handleException("Error generating mail message", e);
        } catch (IOException e) {
            handleException("Error generating mail message", e);
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java

public void enviarEmailHtml(List<String> destinos, String msg, String titulo) {
    //       Recipient's email ID needs to be mentioned.
    String to = "";
    String rodape = "<br/><br/><br/><br/>  <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">"
            + "Esta mensagem  uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> "
            + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>"
            + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>"
            + "</div>";
    for (String d : destinos) {
        if (d.equals(destinos.get(destinos.size() - 1))) {
            to = to.concat(d);/*from  w w w  . j a v a  2 s  .co  m*/
        } else {
            to = to.concat(d.concat(","));
        }
    }

    // Sender's email ID needs to be mentioned
    String from = this.email;
    final String username = this.email;//change accordingly
    final String password = this.senha;//change accordingly

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

    // Get the 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.
        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(titulo);

        // Send the actual HTML message, as big as you like
        message.setContent(msg + rodape, "text/html");

        // Send message
        Transport.send(message);

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