Example usage for javax.mail.internet InternetAddress InternetAddress

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

Introduction

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

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:org.opentides.eventhandler.EmailHandler.java

public InternetAddress[] toInetAddress(String[] strings) throws AddressException {
    if (strings == null)
        return null;
    int count = 0;
    for (int x = 0; x < strings.length; x++) {
        if (StringUtil.isEmpty(strings[x]) || strings[x].trim().length() == 0)
            strings[x] = null;/*  ww w  .  j av a  2 s .co  m*/
        else
            count++;
    }
    if (count == 0)
        return null;
    InternetAddress[] internetAddress = new InternetAddress[count];
    for (int x = 0; x < strings.length; x++) {
        if (strings[x] != null)
            internetAddress[x] = new InternetAddress(strings[x]);
    }
    return internetAddress;
}

From source file:com.redhat.rhn.manager.user.UpdateUserCommand.java

/**
 * Private helper method to validate the user's email address. Puts errors into the
 * errors list./*from   ww w .  j a  v a  2 s.  com*/
 */
private void validateEmail() {
    if (!emailChanged) {
        return; // nothing to verify
    }
    // Make sure user and email are not null
    if (email == null) {
        throw new IllegalArgumentException("Email address is null");
    }

    // Make email is not over the max length
    if (user.getEmail().length() > UserDefaults.get().getMaxEmailLength()) {
        throw new IllegalArgumentException(
                String.format("Email address specified [%s] is too long", user.getEmail()));
    }

    // Make sure set email is valid
    try {
        new InternetAddress(email).validate();
    } catch (AddressException e) {
        throw new IllegalArgumentException("Email address invalid. Cause: " + e.toString());
    }
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public InternetAddress newFromAddress(MimeMessage message) throws MessagingException {
    return new InternetAddress(getFromProperty());
}

From source file:com.redhat.rhn.common.messaging.SmtpMail.java

/**
 * Private helper method to do the heavy lifting of setting the recipients field for
 * a message// w  w  w. j a  v a2 s. c o  m
 * @param type The javax.mail.Message.RecipientType (To, CC, or BCC) for the recipients
 * @param recipIn A string array of email addresses
 */
private void setRecipients(RecipientType type, String[] recipIn) {
    log.debug("setRecipients called.");
    Address[] recAddr = null;
    try {
        List tmp = new LinkedList();
        for (int i = 0; i < recipIn.length; i++) {
            InternetAddress addr = new InternetAddress(recipIn[i]);
            log.debug("checking: " + addr.getAddress());
            if (verifyAddress(addr)) {
                log.debug("Address verified.  Adding: " + addr.getAddress());
                tmp.add(addr);
            }
        }
        recAddr = new Address[tmp.size()];
        tmp.toArray(recAddr);
        message.setRecipients(type, recAddr);
    } catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " + me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}

From source file:eu.scape_project.planning.application.BugReport.java

/**
 * Method responsible for sending a bug report per mail.
 * //from w ww.  j av a 2  s.co  m
 * @param userEmail
 *            email address of the user.
 * @param errorDescription
 *            error description given by the user.
 * @param exception
 *            the exception causing the bug/error.
 * @param requestUri
 *            request URI where the error occurred
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            application name
 * @param plan
 *            the plan where the exception occurred
 * @throws MailException
 *             if the bug report could not be sent
 */
public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri,
        String location, String applicationName, Plan plan) throws MailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        // Date
        builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Plan
        if (plan == null) {
            builder.append("No plan available.").append("\n\n");
        } else {
            builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n");
            builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n");
        }

        // Description
        builder.append("Description:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(errorDescription).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");

        // Request URI
        builder.append("Request URI: ").append(requestUri).append("\n\n");

        // Exception
        if (exception == null) {
            builder.append("No exception available.").append("\n");
        } else {
            builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n");
            builder.append("Exception message: ").append(exception.getMessage()).append("\n");

            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            builder.append("Stacktrace:\n");
            builder.append(SEPARATOR_LINE);
            builder.append(writer.toString());
            builder.append(SEPARATOR_LINE);
        }

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(),
                config.getString("mail.feedback"));

        String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.";
        Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO",
                userMessage, user);
        try {
            utx.begin();
            em.persist(notification);
            utx.commit();
        } catch (Exception e) {
            log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e);
        }

    } catch (MessagingException e) {
        throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to "
                + config.getString("mail.feedback"), e);
    }
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 *
 * @param recipients// w ww  .  j a  v a  2  s  .  com
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, String message) {

    try {

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {
                addressTo[i] = new InternetAddress(recipients[i]);
            }
        }
        send(addressTo, subject, message);

    } catch (Exception ex) {
        //logger.warn(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:eionet.meta.service.EmailServiceImpl.java

/**
 * {@inheritDoc}/*  www  .  j av  a2  s  . co m*/
 */
@Override
public void notifySiteCodeAllocation(String country, AllocationResult allocationResult, boolean adminRole)
        throws ServiceException {
    try {
        SiteCodeAllocationNotification notification = new SiteCodeAllocationNotification();
        notification.setAllocationTime(allocationResult.getAllocationTime().toString());
        notification.setUsername(allocationResult.getUserName());
        notification.setCountry(country);
        notification.setNofAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount()));
        notification.setTotalNofAllocatedCodes(
                Integer.toString(siteCodeDao.getCountryUnusedAllocations(country, false)));
        notification.setNofCodesAllocatedByEvent(Integer.toString(allocationResult.getAmount()));

        SiteCodeFilter filter = new SiteCodeFilter();
        filter.setDateAllocated(allocationResult.getAllocationTime());
        filter.setUserAllocated(allocationResult.getUserName());
        filter.setUsePaging(false);
        SiteCodeResult siteCodes = siteCodeDao.searchSiteCodes(filter);

        notification.setSiteCodes(siteCodes.getList());
        notification.setAdminRole(adminRole);

        final String[] to;
        // if test e-mail is provided, then do not send notification to actual receivers
        if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) {
            notification.setTest(true);
            notification.setTo(StringUtils.join(parseRoleAddresses(country), ","));
            to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ",");
        } else {
            to = parseRoleAddresses(country);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", notification);

        final String text = processTemplate("site_code_allocation.ftl", map);

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
                message.setText(text, false);
                message.setFrom(
                        new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM)));
                message.setSubject("Site codes allocated");
                message.setTo(to);
            }
        };
        mailSender.send(mimeMessagePreparator);

    } catch (Exception e) {
        throw new ServiceException("Failed to send allocation notification: " + e.toString(), e);
    }
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;// ww  w .j  a v a 2s .  c  o m
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public InternetAddress[] newToAddresses(MimeMessage message) throws MessagingException {
    return new InternetAddress[] { new InternetAddress(getToProperty()) };
}

From source file:com.esri.gpt.framework.mail.MailRequest.java

/**
 * Makes an Internet E-Mail address./*from  w w  w. j a va2 s .c  o  m*/
 * @param address the E-Mail address string
 * @return the Internet address
 * @throws AddressException if the E-Mail address is invalid
 */
private InternetAddress makeAddress(String address) throws AddressException {
    return new InternetAddress(address);
}