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:com.gazbert.bxbot.core.mail.EmailAlerter.java

public void sendMessage(String subject, String msgContent) {

    if (sendEmailAlertsEnabled) {

        final Session session = Session.getInstance(smtpProps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpConfig.getAccountUsername(),
                        smtpConfig.getAccountPassword());
            }// w  w  w  .j  a va2s  . c  o m
        });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(smtpConfig.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpConfig.getToAddress()));
            message.setSubject(subject);
            message.setText(msgContent);

            LOG.info(() -> "About to send following Email Alert with message content: " + msgContent);
            Transport.send(message);

        } catch (MessagingException e) {
            // not much we can do here, especially if the alert was critical - the bot is shutting down; just log it.
            LOG.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
        }
    } else {
        LOG.warn("Email Alerts are disabled. Not sending the following message: Subject: " + subject
                + " Content: " + msgContent);
    }
}

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override/*  ww  w.ja va2  s . c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}

From source file:org.openmhealth.dsu.service.EndUserServiceImpl.java

@Override
@Transactional/*w w  w  . ja va 2s.c om*/
public void registerUser(EndUserRegistrationData registrationData) {
    // Determine if username already exists or if e-mail is duplicated
    if (doesUserExist(registrationData.getUsername()) || doesEmailExist(registrationData.getEmailAddress())) {
        throw new EndUserRegistrationException(registrationData);
    }

    // Create new user
    EndUser endUser = new EndUser();
    endUser.setUsername(registrationData.getUsername());
    endUser.setPasswordHash(passwordEncoder.encode(registrationData.getPassword()));
    endUser.setRegistrationTimestamp(OffsetDateTime.now());

    if (registrationData.getEmailAddress() != null) {
        try {
            endUser.setEmailAddress(new InternetAddress(registrationData.getEmailAddress()));
        } catch (AddressException e) {
            throw new EndUserRegistrationException(registrationData, e);
        }
    }

    endUserRepository.save(endUser);
}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * ??eml/*www . jav  a  2 s  .  co  m*/
 * 
 * @param inputStream inputStream
 * @param from from
 * @param tos tos
 * @param properties 
 * @param isCloseInputStream ???InputStream
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static void sendEml(InputStream inputStream, String from, List<String> tos,
        Map<String, String> properties, boolean isCloseInputStream) throws EmailException, MessagingException {
    try {
        // inputStream = new SharedFileInputStream(mailPath);
        Session session = getEmail().getMailSession();
        // session.getProperties().setProperty("mail.smtp.ehlo", "true");
        MimeMessage message = new MimeMessage(session, inputStream);
        if (!Strings.isNullOrEmpty(from)) {
            message.setFrom(new InternetAddress(from));
        }
        // 
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            message.setHeader(name, value);
        }

        if (tos == null || tos.isEmpty()) {
            Transport.send(message);
        } else {
            InternetAddress[] internetAddresses = new InternetAddress[tos.size()];
            int index = 0;
            for (String to : tos) {
                internetAddresses[index] = new InternetAddress(to);
                index++;
            }
            Transport.send(message, internetAddresses);
        }
    } finally {
        if (isCloseInputStream) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

From source file:com.cloudbees.demo.beesshop.service.MailService.java

public void sendOrderConfirmation(ShoppingCart shoppingCart, String recipient) {

    try {//from w w w  .  ja v  a2  s  .  c o  m
        Message msg = new MimeMessage(mailSession);

        msg.setFrom(fromAddress);
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        msg.setSubject("[BeesShop] Order Confirmation: " + shoppingCart.getItems() + " items - "
                + shoppingCart.getPrettyPrice());

        String message = "ORDER CONFIRMATION\n" + "\n" + "* Purchased items: " + shoppingCart.getItemsCount()
                + "\n" + "* Price: " + shoppingCart.getPrettyPrice() + "\n";

        for (ShoppingCart.ShoppingCartItem item : shoppingCart.getItems()) {
            message += "   * " + item.getQuantity() + "x" + item.getProduct().getName() + "\n";
        }

        msg.setContent(message, "text/plain");

        Transport.send(msg);
        auditLogger.info("Sent to {} shopping cart with value of '{}'", recipient,
                shoppingCart.getPrettyPrice());
        sentEmailCounter.incrementAndGet();
    } catch (MessagingException e) {
        logger.warn("Exception sending order confirmation email to {}", recipient, e);
    }
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    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");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from  w  w  w .  ja v  a2s .c om*/
    });

    try {
        // Create a default MimeMessage object.
        javax.mail.Message message1 = new MimeMessage(session);

        // Set From: header field of the header.
        message1.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

        System.out.println("Sent message successfully....");

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

From source file:com.otz.plugins.transport.aws.ses.SpringEmailSender.java

public void send(String templateName, Locale locale, String to, Map<String, String> parameters)
        throws MessagingException {

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(emailTemplateRepository.getFrom(templateName, locale)));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(emailTemplateRepository.getSubject(templateName, locale));
    msg.setContent(emailTemplateRepository.getContent(templateName, locale, parameters),
            emailTemplateRepository.getContentType(templateName, locale));

    try {/*from w  ww .  j a v  a  2  s . c om*/
        // Create a transport.
        transport = session.getTransport();
        transport.connect(emailConfigParameters.getHost(), emailConfigParameters.getAccessKey(),
                emailConfigParameters.getSecretKey());
        transport.sendMessage(msg, msg.getAllRecipients());

    } catch (Exception e) {

        // TODO deal with failure to send
        // send message to hipchat
        e.printStackTrace();
    }

}

From source file:com.pinterest.deployservice.email.SMTPMailManagerImpl.java

public void send(String to, String title, String message) throws Exception {
    Session session = Session.getDefaultInstance(properties, getAuthenticator());
    // Create a default MimeMessage object.
    MimeMessage mimeMessage = new MimeMessage(session);
    // Set From: header field of the header.
    mimeMessage.setFrom(new InternetAddress(adminAddress));
    // Set To: header field of the header.
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // Set Subject: header field
    mimeMessage.setSubject(title);//from w  ww  .j ava  2 s  . c o  m
    // Now set the actual message
    mimeMessage.setText(message);
    // Send message
    Transport.send(mimeMessage);
}

From source file:edu.washington.iam.tools.IamMailSender.java

public void sendWithOwnerCc(IamMailMessage msg, DNSVerifier verifier, List<String> cns) {

    MimeMessage mime = genMimeMessage(msg);
    try {//w  ww .j  av a 2 s  .  co  m
        List<String> owners = new Vector();
        for (int i = 0; i < cns.size(); i++)
            verifier.isOwner(cns.get(i), null, owners);
        Address[] oAddrs = new Address[owners.size()];
        for (int i = 0; i < owners.size(); i++) {
            oAddrs[i] = new InternetAddress(owners.get(i) + "@uw.edu");
            // log.debug(" cc to: " + owners.get(i));
        }
        mime.setRecipients(RecipientType.CC, oAddrs);
        mailSender.send(mime);
    } catch (DNSVerifyException ex) {
        log.error("checking dns: " + ex.getMessage());
    } catch (MessagingException e) {
        log.error("iam mail failure: " + e);
    }
}

From source file:mitm.common.mail.MailAddressTest.java

@Test
public void testValid() throws Exception {
    MailAddress address = new MailAddress("test@example.com");
    assertEquals("test", address.getUser());
    assertEquals("example.com", address.getHost());

    address = new MailAddress("  test@example.com  ");
    assertEquals("test", address.getUser());
    assertEquals("example.com", address.getHost());

    address = new MailAddress("\"test.\"@example.com  ");
    assertEquals("\"test.\"", address.getUser());
    assertEquals("example.com", address.getHost());

    // source routing
    address = new MailAddress(" @xxx:test@example.com  ");
    assertEquals("test", address.getUser());
    assertEquals("example.com", address.getHost());

    // dot num ([])
    address = new MailAddress("test@[1.2.3.4]");
    assertEquals("test", address.getUser());
    assertEquals("1.2.3.4", address.getHost());

    assertEquals("test@exa-mple.com", new InternetAddress("test@exa-mple.com").getAddress());
}