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:hudson.maven.reporters.MavenMailerTest.java

public Mailbox runMailTest(boolean perModuleEamil) throws Exception {

    final DescriptorImpl mailDesc = Jenkins.getInstance().getDescriptorByType(Mailer.DescriptorImpl.class);

    // intentionally give the whole thin in a double quote
    Mailer.descriptor().setAdminAddress(EMAIL_ADMIN);

    String recipient = "you <you@sun.com>";
    Mailbox yourInbox = Mailbox.get(new InternetAddress(recipient));
    yourInbox.clear();//from  w ww .j  ava  2  s  .c  o m

    j.configureDefaultMaven();
    MavenModuleSet mms = j.createMavenProject();
    mms.setGoals("test");
    mms.setScm(
            new ExtractResourceSCM(getClass().getResource("/hudson/maven/maven-multimodule-unit-failure.zip")));
    j.assertBuildStatus(Result.UNSTABLE, mms.scheduleBuild2(0).get());

    MavenMailer m = new MavenMailer();
    m.recipients = recipient;
    m.perModuleEmail = perModuleEamil;
    mms.getReporters().add(m);

    mms.scheduleBuild2(0).get();

    Address[] senders = yourInbox.get(0).getFrom();
    assertEquals(1, senders.length);
    assertEquals("me <me@sun.com>", senders[0].toString());

    return yourInbox;
}

From source file:org.cgiar.dapa.ccafs.tpe.service.impl.TPEMailService.java

@Override
public void notifyAdmin(final Map<String, Object> templateVariables) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(supportEmail);
            message.setFrom(new InternetAddress(adminEmail));
            message.setSubject(SUBJECT_ADMIN);
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "templates/notify-admin.vm", "UTF-8", templateVariables);
            log.info(body);/*from w  w  w  .  j  a  v a 2  s. co m*/
            message.setText(body, true);
        }
    };
    this.mailSender.send(preparator);

}

From source file:edu.utah.further.core.util.registry.UTestRegistry.java

/**
 * A factory template method of grid nodes.
 *
 * @param type/* w  w w  . j a  va  2s.com*/
 * @param name
 * @return
 */
private static Node newNode(final NodeType type, final String name) {
    final String domain = replace(name.toLowerCase(), " ", "") + ".net";
    InternetAddress admin;
    try {
        admin = new InternetAddress("admin@" + domain);
    } catch (final AddressException e) {
        throw new ApplicationException("Bad admin address", e);
    }

    switch (type) {
    case SOURCE: {
        return new SourceImpl(name, name + " description", "http://" + domain, admin);
    }

    case REGISTRY: {
        return new RegistryImpl(name, name + " description", "http://" + name.toLowerCase() + ".net", admin);
    }

    default: {
        return null;
    }
    }
}

From source file:org.tsm.concharto.service.EmailService.java

/**
 *
 * @param subject//from w  w  w.j ava 2 s. c om
 * @param body
 * @param sender
 * @param recipients
 */
public void SendIndividualMessages(String subject, String body, InternetAddress sender, String[] recipients) {
    int emailErrorCount = 0;
    for (int i = 0; i < recipients.length; i++) {
        String recipientEmailAddress = recipients[i];
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        try {
            message.setText(body);
            message.setSubject(subject);
            message.setFrom(sender);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress));
            sendMessage(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            emailErrorCount++;
        }
    }
    if (emailErrorCount > 0) {
        String message = emailErrorCount + " out of " + recipients.length + " emails could not be sent.";
        log.error(message);
    }
}

From source file:com.assetmanager.service.mail.MailService.java

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user//from  w  w  w  . j a v a  2 s. c  o  m
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();

    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));

    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));

    textPart.setContent(messageSource.getMessage("mail.body.txt",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");

    htmlPart.setContent(messageSource.getMessage("mail.body.html",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");

    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    Transport.send(message);
}

From source file:de.kaffeeshare.server.NamespaceCheck.java

private JSONObject checkNamespace(String namespace) {
    JSONObject json = new JSONObject();
    try {/*from   w w w .  ja v  a  2  s.  c  o m*/

        // By convention, all namespaces starting with "_" (underscore) are reserved for system use.
        if (namespace.charAt(0) == '_') {
            json.put("status", "error");
            return json;
        }

        // check if namespace is valid 
        try {
            DatastoreManager.setNamespace(namespace);
        } catch (Exception e) {
            json.put("status", "error");
            return json;
        }

        // check if email and jabber address are valid!
        // I believe a valid email address also a valid jabber address
        // so I only check for valid email address
        try {
            InternetAddress emailAddr = new InternetAddress(namespace + "@abc.com");
            emailAddr.validate();
        } catch (AddressException ex) {
            json.put("status", "error");
            return json;
        }

        // check if namespace is empty
        if (!DatastoreManager.getDatastore().isEmpty()) {
            json.put("status", "use");
            return json;
        }

        json.put("status", "success");
        return json;
    } catch (JSONException e) {
        log.warning("JSON exception @ namespace check");
        e.printStackTrace();
        return null;
    }
}

From source file:gov.nih.nci.caarray.util.EmailUtil.java

private static MimeMessage constructMessage(List<String> mailRecipients, String from, String mailSubject)
        throws MessagingException {
    Validate.notEmpty(mailRecipients, "No email recipients are specified");
    if (StringUtils.isEmpty(mailSubject)) {
        LOG.info("No email subject specified");
    }//from  w w w.j a va  2 s .c o  m

    List<Address> addresses = new ArrayList<Address>();
    for (String recipient : mailRecipients) {
        addresses.add(new InternetAddress(recipient));
    }

    MimeMessage message = new MimeMessage(MAILSESSION);
    message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()]));
    message.setFrom(new InternetAddress(from));
    message.setSubject(mailSubject);

    return message;
}

From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException {
    MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties()));
    msg.setFrom(new InternetAddress("alert@srotya.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com"));
    msg.setSubject("test mail");
    msg.setContent("Hello", "text/html");
    Transport.send(msg);//from w  w w  .  j av  a  2s  .  c  o  m
    MailService ms = new MailService();
    ms.init(new HashMap<>());
    Alert alert = new Alert();
    alert.setBody("test");
    alert.setId((short) 0);
    alert.setMedia("test");
    alert.setSubject("test");
    alert.setTarget("alert@srotya.com");
    ms.sendMail(alert);
    assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize());
    System.err.println("Mail sent");
}

From source file:net.naijatek.myalumni.util.mail.FreeMarkerTemplateMailerImpl.java

public void mail(final String email, final Map map, final String bodyTemplatePrefix,
        final String subjectTemplatePrefix) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));

            ////w ww  .  ja  v  a 2  s .c  o  m
            // Get the subject
            //
            //BodyPart subjectPart = new MimeBodyPart();
            Template subjectTextTemplate = configuration.getTemplate(subjectTemplatePrefix);
            final StringWriter subjectTextWriter = new StringWriter();

            try {
                subjectTextTemplate.process(map, subjectTextWriter);
            } catch (TemplateException e) {
                throw new MailPreparationException("Can't generate Subject Text", e);
            }
            mimeMessage.setSubject(subjectTextWriter.toString());

            //
            // Create a "text" Multipart message
            //

            Template bodyTextTemplate = configuration.getTemplate(bodyTemplatePrefix);
            final StringWriter bodyTextWriter = new StringWriter();

            try {
                bodyTextTemplate.process(map, bodyTextWriter);
            } catch (TemplateException e) {
                throw new MailPreparationException("Can't generate Body Text", e);
            }
            mimeMessage.setText(bodyTextWriter.toString());

            /*                // @TODO - This part handles sending an attachement
                            textPart.setDataHandler(new DataHandler(new DataSource() {
            public InputStream getInputStream() throws IOException {
                return new StringBufferInputStream(bodyTextWriter.toString());
            }
            public OutputStream getOutputStream() throws IOException {
                throw new IOException("Read-only data");
            }
            public String getContentType() {
                return "text/plain";
            }
            public String getName() {
                return "main";
            }
                            }));
                            mp.addBodyPart(textPart);*/

            /*                // Create a "HTML" Multipart message
                            Multipart htmlContent = new MimeMultipart("related");
                            BodyPart htmlPage = new MimeBodyPart();
                            Template htmlTemplate = configuration.getTemplate(templatePrefix + "-html.ftl");
                            final StringWriter htmlWriter = new StringWriter();
                            try {
            htmlTemplate.process(map, htmlWriter);
                            } catch (TemplateException e) {
            throw new MailPreparationException("Can't generate HTML subscription mail", e);
                            }
                            htmlPage.setDataHandler(new DataHandler(new DataSource() {
            public InputStream getInputStream() throws IOException {
                return new StringBufferInputStream(htmlWriter.toString());
            }
            public OutputStream getOutputStream() throws IOException {
                throw new IOException("Read-only data");
            }
            public String getContentType() {
                return "text/html";
            }
            public String getName() {
                return "main";
            }
                            }));
                            htmlContent.addBodyPart(htmlPage);
                            BodyPart htmlPart = new MimeBodyPart();
                            htmlPart.setContent(htmlContent);
                            mp.addBodyPart(htmlPart);
                    
                            mimeMessage.setContent(mp);*/
        }
    };
    mailSender.send(preparator);
}

From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *//* ww  w.java2  s .com*/
public boolean send() {

    try {
        // 2005-11-27 RSC always requires authentication.
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", host.getAddress());
        /*
         * 2005-11-27 RSC
         * Since webmail.us is starting to make other ports available
         * as Comcast blocks port 25.
         */
        props.put("mail.smtp.port", host.getPort());

        Session s = Session.getInstance(props, null);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return true;
}