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.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail2(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from ww  w  . j av  a  2s.co  m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Bienvenido al SISTEMA INFORM?TICO DEL REGISTRO NACIONAL DE ADOPCIONES, "
                + "sus credenciales para inscribirse al taller son las siguientes:" + "\n\n Usuario: " + user
                + "\n\n Contrasea: " + pass_plano
                //                    + "\n\n Para ingresar al sistema realizar lo siguiente, "
                //                    + "\n\n"
                //                    + "\n\n"
                //                    + "\n\n A. Click directamente en el siguiente link: "
                //                    + "\n\n"
                //                    + "\n\n       1. Click: http://app.mimp.gob.pe:8080/sirna "
                //                    + "\n\n       2. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n B. En caso no funcione el link, ingresar al sistema desde la pgina web: "
                //                    + "\n\n"
                //                    + "\n\n       1. Ingresar a la pgina web: www.mimp.gob.pe "
                //                    + "\n\n       2. En la barra de men Direcciones Generales? submen Vicemin. Pob. Vulnerables? seleccionar Adopciones? "
                //                    + "\n\n       3. Click en SIRNA Sistema Informtico del Registro Nacional de Adopciones? "
                //                    + "\n\n       4. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n A travs del SIRNA usted podr realizar las siguientes acciones: "
                //                    + "\n\n"
                //                    + "\n\n       - Inscribirse a uno de los talleres programados. "
                //                    + "\n\n       - Descargar las lecturas de su taller. "
                //                    + "\n\n       - Revisar el estado del proceso de adopcin. "
                //                    + "\n\n       - Cambiar su contrasea. "
                //                    + "\n\n"
                //                    + "\n\n Para continuar con el proceso, por favor ingresar al sistema e inscribirse a uno de los talleres programados, hasta un da antes de inicio del taller y/o las bacantes se  "
                //                    + "\n\n encuentres disponibles. "
                + "\n\n"
                + "\n\n De tener alguna complicacin y no fue posible su ingreso al sistema, comunicarse inmediatamente con la unidad de adopcin correspondiente.  "
                + "\n\n" + "\n\n Atentamente, " + "\n\n" + "\n\n Direccin General de Adopciones " + "\n\n"
                + "\n\n Ministerio de la Mujer y Poblaciones Vulnerables " + "\n\n ");

        Transport.send(message);

        /*  } catch (Exception ex) {
         */
    } catch (Exception ex) {

    }

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

From source file:com.mobileman.projecth.business.MailManagerTest.java

/**
 * @throws Exception/*  w  w w .  j a  va  2s .  co  m*/
 */
@Test
public void sendMessageToAdmin_EmptyFrom() throws Exception {

    mailManager.sendMessageToAdmin(" ", "subject1", "body");
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(new InternetAddress("projecth@projecth.com"), messages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("mitglied@projecth.com"),
            messages.get(0).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("subject1", messages.get(0).getMimeMessage().getSubject());
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*from www .  j  a  v a2  s. c om*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:fr.xebia.cocktail.MailService.java

public void sendCocktail(Cocktail cocktail, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);/* w w  w . j a v  a  2 s  . com*/
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[Cocktail] " + cocktail.getName());
    String message = cocktail.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(cocktail.getInstructions()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    Transport.send(msg);
    auditLogger.info("Sent to {} cocktail '{}'", recipient, cocktail.getName());
    sentEmailCounter.incrementAndGet();
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

/**
 * @param useSmtps in order to use smtp.gmail.com (for testing)
 * @throws AddressException //from w  w  w . j  a va 2s. c  o m
 */
public SmtpEmailService(String host, String username, String replyTos, String password, boolean useSmtps)
        throws AddressException {
    this.host = host;
    this.username = username;
    this.password = password;
    this.useSmtps = useSmtps;
    if (replyTos != null) {
        String[] sreplyTos = replyTos.split(",");
        Set<InternetAddress> set = Sets.newHashSet();
        for (String s : sreplyTos) {
            if (!StringUtils.isEmpty(s))
                set.add(new InternetAddress(s));
        }
        this.replyTos = set.toArray(new InternetAddress[] {});
    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {//from w w w . ja  v a2 s . co m
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:edu.utah.further.core.util.composite.UTestComposite.java

/**
 * A factory template method of grid nodes.
 * /*  ww w . ja v  a  2 s. c om*/
 * @param type
 * @param name
 * @return
 */
private static Source newSource(final SourceType 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 DATA: {
        return new DataSource(name, name + " description", "http://" + domain, admin);
    }

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

    default: {
        return null;
    }
    }
}

From source file:com.mobileman.projecth.business.messages.MessageServiceTest.java

/**
 * @throws Exception//w  w w.  j ava 2 s  . c  om
 */
@Test
public void markAsSpam() throws Exception {
    Message message = messageService.findAll().get(0);
    assertFalse(message.isSpam());

    List<WiserMessage> mailMessages = wiser.getMessages();
    assertEquals(0, mailMessages.size());

    messageService.markAsSpam(message.getId(), true);
    flushSession();

    message = messageService.findById(message.getId());
    assertTrue(message.isSpam());

    mailMessages = wiser.getMessages();
    assertEquals(1, mailMessages.size());
    assertEquals(new InternetAddress("doc1@projecth.com"), mailMessages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("spam@projecth.com"),
            mailMessages.get(0).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(0).getMimeMessage().getSubject());
}

From source file:com.hiperium.bo.manager.mail.EmailMessageManager.java

/**
 * Sends an email with the new user password.
 * /*from  w w w . j a  va  2s . co m*/
 * @param user
 * @throws javax.mail.internet.AddressException
 * @throws javax.mail.MessagingException
 */
public void sendNewPassword(User user) {
    try {
        this.log.debug("sendNewPassword() - START");
        // Create the corresponding user locale.
        Locale locale = null;
        if (StringUtils.isBlank(user.getLanguageId())) {
            locale = Locale.getDefault();
        } else {
            locale = new Locale(user.getLanguageId());
        }
        ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale);

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", CloudEmailUser.HOST);
        properties.setProperty("mail.user", CloudEmailUser.USERNAME);
        properties.setProperty("mail.password", CloudEmailUser.PASSWORD);
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS));
        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
        // Set Subject: header field
        message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT));
        // Send the actual HTML message, as big as you like
        message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT),
                user.getFirstname(), user.getLastname(), user.getPassword()), "text/html");
        // Send message
        Transport.send(message);
        this.log.debug("sendNewPassword() - END");
    } catch (AddressException e) {
        this.log.error("AddressException to send email to " + user.getEmail(), e);
    } catch (MessagingException e) {
        this.log.error("MessagingException to send email to " + user.getEmail(), e);
    }
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email.//  w w  w. j  a  v  a2s  .  c o m
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}