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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);//from   w  w  w .j  ava 2  s .c o m
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public void sendEmail(String to, String subject, String body) {
    final String fromUser = fromMail;
    final String passUser = password;
    Properties props = new Properties();
    props.put("mail.smtp.host", smtp);
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.auth", mailAuth);
    props.put("mail.smtp.port", port);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromUser, passUser);
        }/*ww w .j a v  a2 s  . c om*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromUser));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:azkaban.reportal.util.ReportalHelper.java

/**
 * Returns true if the given email is valid and false otherwise.
 * @param email/*  w ww . j av  a2s .  co m*/
 * @return
 */
public static boolean isValidEmailAddress(String email) {
    if (email == null) {
        return false;
    }

    boolean result = true;
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
    } catch (AddressException ex) {
        result = false;
    }
    return result;
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateSigningCertAvailable() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "test@example.com";
    String to = "to@example.com";

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new FileInputStream("test/resources/testdata/keys/testCertificates.p12"),
            "test".toCharArray());

    SystemServices.getKeyAndCertificateWorkflow().importKeyStore(keyStore, MissingKey.ADD_CERTIFICATE);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from ww w .  j a va 2 s. co  m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//from  www  . j av a 2  s .  com
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:mitm.common.tools.SendMail.java

private void sendMultiThreaded(final MailTransport mailSender, final MimeMessage message,
        final Address[] recipients) throws InterruptedException {
    ExecutorService threadPool = Executors.newCachedThreadPool();

    final Semaphore semaphore = new Semaphore(threads, true);

    final long startTime = System.currentTimeMillis();

    for (int i = 1; i <= count; i++) {
        long threadStart = System.currentTimeMillis();

        semaphore.acquireUninterruptibly();

        threadPool.execute(new Runnable() {
            @Override//from  ww  w. ja va 2 s . c o  m
            public void run() {
                try {
                    MimeMessage clone = MailUtils.cloneMessage(message);

                    int sent = sentCount.incrementAndGet();

                    if (uniqueFrom) {
                        Address[] froms = clone.getFrom();

                        if (froms != null && froms.length > 0) {
                            clone.setFrom(
                                    new InternetAddress(sent + EmailAddressUtils.getEmailAddress(froms[0])));
                        }
                    }

                    mailSender.sendMessage(clone, recipients);

                    long timePassed = DateTimeUtils
                            .millisecondsToSeconds(System.currentTimeMillis() - startTime);

                    StrBuilder sb = new StrBuilder();

                    sb.append("Message\t" + sent + "\tsent.");

                    if (timePassed > 0) {
                        float msgPerSec = (float) sent / timePassed;

                        sb.append("\tmessages/second\t" + String.format("%.2f", msgPerSec));
                    }

                    logger.info(sb.toString());
                } catch (MessagingException e) {
                    logger.error("Error sending message.", e);
                } finally {
                    semaphore.release();
                }
            }
        });

        if (forceQuit.get()) {
            break;
        }

        if (throtllingSemaphore != null) {
            /* for throttling the sending of emails */
            throtllingSemaphore.acquire();
        } else {
            /* no throttling so use delay */
            long sleepTime = delay - (System.currentTimeMillis() - threadStart);

            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
        }
    }

    threadPool.shutdown();
    threadPool.awaitTermination(30, TimeUnit.SECONDS);

    waitForReceiveThreads();

    logger.info("Total sent: " + sentCount.intValue() + ". Total time: "
            + DateTimeUtils.millisecondsToSeconds(System.currentTimeMillis() - startTime) + " (sec.)");
}

From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java

private Set<InternetAddress> buildCulpritList(BuildListener listener, Set<User> culprits)
        throws AddressException {
    Set<InternetAddress> r = new HashSet<InternetAddress>();
    for (User a : culprits) {
        String adrs = Util.fixEmpty(a.getProperty(Mailer.UserProperty.class).getAddress());
        if (debug)
            listener.getLogger().println("  User " + a.getId() + " -> " + adrs);
        if (adrs != null)
            r.add(new InternetAddress(adrs));
        else {//  ww w .  ja  v  a2 s  .c o m
            listener.getLogger().println(Messages.MailSender_NoAddress(a.getFullName()));
        }
    }
    return r;
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateWelcomeMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com", "Welcome",
            "welcome_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Welcome", message.getSubject());
    Assert.assertEquals(_WELCOME_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:esg.node.components.notification.ESGNotifier.java

private boolean sendNotification(String userid, String userAddress, String messageText) {
    Message msg = null;/*  w  w w  . j  av  a2s. c om*/
    boolean success = false;
    String myAddress = null;

    try {
        msg = new MimeMessage(session);
        msg.setHeader("X-Mailer", "ESG DataNode IshMailer");
        msg.setSentDate(new Date());
        myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov");
        msg.setFrom(new InternetAddress(myAddress));
        msg.setSubject(subject + "ESG File Update Notification");

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress));
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress));

        msg.setText(messageText);

        Transport.send(msg);
        success = true;
    } catch (MessagingException ex) {
        log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject
                + ")\n" + messageText + "\n", ex);
    }

    msg = null; //gc niceness

    return success;
}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Method to send a test message./*from   w w  w .  j a  va 2  s .c o m*/
 * 
 * @throws MessagingException
 *           if sending the message failed
 */
private void sendTestMessage(String recipient) throws MessagingException {
    MimeMessage message = createMessage();
    message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject("Test from Weblounge");
    message.setText("Hello world");
    message.saveChanges();
    send(message);
}