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:immf.SendMailBridge.java

private static List<InternetAddress> getRecipients(MimeMessage msg, String type) throws MessagingException {
    List<InternetAddress> r = new ArrayList<InternetAddress>();
    String[] headers = msg.getHeader(type);
    if (headers == null) {
        return r;
    }//from   ww  w  .java2 s .  co m
    for (String h : headers) {
        InternetAddress[] addrs = InternetAddress.parse(h);
        CollectionUtils.addAll(r, addrs);
    }
    return r;
}

From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    Properties props = System.getProperties();
    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);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {//  w w w .  j  a  v  a2  s  .c  o m
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Hospital Organization");
        mimeMessage.setText(message);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:immf.ImodeNetClient.java

private void loadCsvAddressBook(AddressBook ab) throws IOException {
    if (this.csvAddressBook == null) {
        return;/*from   w  w w. j a  v  a2 s.c om*/
    }
    File csvFile = new File(this.csvAddressBook);
    if (!csvFile.exists()) {
        log.info("# CSV(" + this.csvAddressBook + ")????");
        return;
    }
    log.info("# CSV????");
    BufferedReader br = null;
    FileReader fr = null;
    try {
        // ???
        // wrapper.conf?-Dfile.encoding=UTF-8?????UTF-8??
        fr = new FileReader(csvFile);
        br = new BufferedReader(fr);
        int id = 0;

        String line = null;
        while ((line = br.readLine()) != null) {
            // :
            // ,?
            id++;
            try {
                String[] field = line.split(",");
                if (field.length < 2) {
                    continue;
                }
                InternetAddress[] addrs = InternetAddress.parse(field[0]);
                if (addrs.length == 0)
                    continue;
                ImodeAddress ia = new ImodeAddress();
                ia.setMailAddress(addrs[0].getAddress());
                ia.setName(field[1]);
                ia.setId(String.valueOf(id));
                ab.addCsvAddr(ia);
                log.debug("ID:" + ia.getId() + " / Name:" + ia.getName() + " / Address:" + ia.getMailAddress());

            } catch (Exception e) {
                log.warn("CSV(" + id + ")??????[" + line + "]");
            }
        }
        br.close();
    } catch (Exception e) {
        log.warn("loadCsvAddressBook " + this.csvAddressBook + " error.", e);

    } finally {
        Util.safeclose(br);
        Util.safeclose(fr);
    }
}

From source file:org.jivesoftware.util.StringUtils.java

/**
 * Returns true if the string passed in is a valid Email address.
 *
 * @param address Email address to test for validity.
 * @return true if the string passed in is a valid email address.
 *///from ww  w .  j  a v  a 2 s  .co m
public static boolean isValidEmailAddress(String address) {
    if (address == null) {
        return false;
    }

    if (!address.contains("@")) {
        return false;
    }

    try {
        InternetAddress.parse(address);
        return true;
    } catch (AddressException e) {
        return false;
    }
}

From source file:controllers.Send.java

public static Result sendTransactionViaEmail(String id, String recipient) {
    // Send email
    //      models.Customer sender = models.Customer.find.byId(transactionForm.get().sender.id);

    Logger.debug("Tyrying to send transaction to " + recipient);
    if (recipient == null) {
        // TODO get from beneficiary email
        flash("error", "Unidentified sender email");
    }/*from  ww  w  .ja  va  2s. c  o  m*/

    try {
        JsonNode result = ApiHelper.transactionDetail(id);
        Html html = receipt_email.render(result);

        InternetAddress[] tos = InternetAddress.parse(recipient);
        if ((tos.length > 0)) {
            InternetAddress to = tos[0];
            to.validate();
            //TODO Check if valid
            ApiHelper.sendHtmlEmail(null, tos[0], "Bukti transaksi pengiriman uang", html);
            flash("success", "Transaction email has been sent to sender email <strong>"
                    + recipient.replaceAll("<", "(").replaceAll(">", ")") + "</strong>");
        } else {
            //            flash("error", "Unable to send email to "+recipient);
        }
    } catch (EmailException e) {
        e.printStackTrace();
        Logger.error(e.getMessage(), e);
        flash("error", "Unable to send email to " + recipient);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Logger.error(e.getMessage(), e);
        flash("error", "Unable to send email to " + recipient);
    } catch (AddressException e) {
        e.printStackTrace();
        Logger.error(e.getMessage(), e);
        flash("error", "Unable to send email to " + recipient);
    }

    return redirect(routes.Send.receipt(id));
}

From source file:immf.ImodeNetClient.java

private void loadVcAddressBook(AddressBook ab) throws IOException {
    if (this.vcAddressBook == null) {
        return;/*from  w  w  w .j a  v a 2s  . c  o  m*/
    }
    File vcFile = new File(this.vcAddressBook);
    if (!vcFile.exists()) {
        log.info("# vCard(" + this.vcAddressBook + ")????");
        return;
    }
    log.info("# vCard????");
    FileInputStream fis = null;
    byte[] vcData = null;
    try {
        fis = new FileInputStream(vcFile);
        vcData = new byte[(int) vcFile.length()];
        fis.read(vcData);
    } catch (Exception e) {
        log.warn("loadVcAddressBook " + this.vcAddressBook + " error.", e);
    } finally {
        Util.safeclose(fis);
    }

    int id = 0;
    boolean vcBegin = false;
    String vcName = null;
    String vcEmail = null;

    int lineStart = 0;
    int lineLength = 0;

    for (int i = lineStart; i <= vcFile.length(); i++) {
        try {
            if (i == vcFile.length() || vcData[i] == '\n') {
                String line = new String(vcData, lineStart, lineLength);
                int curLineStart = lineStart;
                int curLineLength = lineLength;

                lineStart = i + 1;
                lineLength = 0;

                String field[] = line.split(":");
                if (field[0].equalsIgnoreCase("BEGIN")) {
                    vcBegin = true;
                    vcName = null;
                    vcEmail = null;
                    id++;
                }
                if (vcBegin == true && field[0].equalsIgnoreCase("END")) {
                    vcBegin = false;

                    if (vcName == null || vcEmail == null)
                        continue;

                    String vcEmails[] = vcEmail.split(";");
                    for (int j = 0; j < vcEmails.length; j++) {
                        InternetAddress[] addrs = InternetAddress.parse(vcEmails[j]);
                        if (addrs.length == 0)
                            continue;
                        ImodeAddress ia = new ImodeAddress();
                        ia.setMailAddress(addrs[0].getAddress());
                        ia.setName(vcName);
                        ia.setId(String.valueOf(id + "-" + (j + 1)));
                        ab.addVcAddr(ia);
                        log.debug("ID:" + ia.getId() + " / Name:" + ia.getName() + " / Address:"
                                + ia.getMailAddress());
                    }
                }

                if (vcBegin != true || field.length < 2)
                    continue;

                String label[] = field[0].split(";");
                String value[] = field[1].split(";");
                // ??
                if (label[0].equalsIgnoreCase("FN")) {
                    vcName = field[1].replace(";", " ").trim();
                    if (label.length < 2)
                        continue;
                    String option[] = label[1].split("=");
                    if (option.length < 1 || !option[0].equalsIgnoreCase("CHARSET"))
                        continue;
                    int valueStart = curLineStart;
                    for (int pos = curLineStart; pos < curLineStart + curLineLength; pos++) {
                        if (vcData[pos] == ':') {
                            valueStart = pos + 1;
                            break;
                        }
                    }
                    vcName = new String(vcData, valueStart, curLineLength - (valueStart - curLineStart),
                            option[1]).replace(";", " ").trim();

                }
                // EMAIL
                if (label[0].equalsIgnoreCase("EMAIL")) {
                    if (vcEmail == null)
                        vcEmail = value[0];
                    else
                        vcEmail = vcEmail + ';' + value[0];
                }

            } else if (vcData[i] != '\r') {
                lineLength++;
            }
        } catch (Exception e) {
            log.warn("vCard(" + id + ")??????");
        }
    }
}

From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java

private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed
    // TODO add your handling code here:

    int selectedRow = productTable.getSelectedRow();
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select a Product from the Table");
        return;//  w  ww . j  a  v  a  2s.c o  m
    }

    Product product = (Product) productTable.getValueAt(selectedRow, 0);
    int quantity = (Integer) quantitySpinner.getValue();
    if (quantity == 0) {
        JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!");
        return;
    }

    if (product != null) {
        updateQuantity(product, quantity, SUBTRACT);
    }
    String medName = product.getProdName();

    Employee patient = (Employee) patientCombo1.getSelectedItem();
    patient.getMedicalRecord().setMedicinePrescribed(medName);
    String email = patient.getEmail();

    if (email.trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!");
        return;
    }

    if (isValidEmailAddress(email)) {
        String uuid = UUID.randomUUID().toString();
        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");

        Properties props = new Properties();
        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("neelzsaxena@gmail.com", "painforever24");
            }

        }

        );
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Prescribed Medicines");
            message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:"
                    + quantity + '\n' + "The unique barcode is:" + uuid);
            Transport.send(message);
            populateTable();
            JOptionPane.showMessageDialog(null, "message sent");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "message failed");
        }

    } else {
        JOptionPane.showMessageDialog(null, "Invalid Email Id");
        return;
    }

    //        String uuid = UUID.randomUUID().toString();
    //        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");
    //        
    //        Properties props = new Properties();
    //        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("neelzsaxena@gmail.com", "painforever24");
    //                    }
    //   
    //            }
    //
    //   );
    //        try{
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
    //            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
    //            message.setSubject("Prescribed Medicines");
    //            message.setText("The medicine Prescribed is :" +medName + '\n'+
    //                            "The Quantity authorized is:"+quantity + '\n'+
    //                            "The unique barcode is:"+uuid);
    //                Transport.send(message);
    //                    populateTable();
    //                    JOptionPane.showMessageDialog(null,"message sent");
    //            }catch(Exception e){
    //                JOptionPane.showMessageDialog(null,"message failed");
    //            }

}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    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);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {/* w w w. ja v  a2 s  . c  o  m*/
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    Properties props = new Properties();
    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("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//  w ww  . j a v  a 2  s  . c o m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

private String getEmailAddressFromMessage(Message m) throws MessagingException {
    Address[] sender = m.getFrom();// ww w .ja v a2s . c om
    String creatorEmail = "";
    if (sender.length > 0) {
        if (sender[0] instanceof InternetAddress) {
            creatorEmail = ((InternetAddress) sender[0]).getAddress();
        } else {
            try {
                InternetAddress ia[] = InternetAddress.parse(sender[0].toString());
                if (ia.length > 0) {
                    creatorEmail = ia[0].getAddress();
                }
            } catch (AddressException ae) {
            }
        }
    }

    return creatorEmail;
}