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.mobileman.projecth.business.MailManagerTest.java

/**
 * @throws Exception/*  w ww.  java  2 s.  c  om*/
 */
@Test
public void sendMessageToAdmin() throws Exception {

    mailManager.sendMessageToAdmin("aaa@gmail.com", "subject1", "body");
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(new InternetAddress("aaa@gmail.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:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaVerificacionEmailImp.java

@Override
public void enviarAlerta(List<AlertaVerificacion> alertas) {
    try {//  w ww . ja  v  a 2s  . co  m
        for (AlertaVerificacion x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta de Verificacin");
            ST contenido = new ST(contenidoRaw);
            contenido.add("placas", x.getPlacas());
            contenido.add("periodo", x.getPeriodo());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openmhealth.dsu.repository.EndUserRepositoryIntegrationTests.java

protected EndUser newUser() {

    EndUser endUser = new EndUser();

    endUser.setUsername(TEST_USERNAME);/*w  w  w  .j a  v  a  2  s . c  om*/
    endUser.setPasswordHash(TEST_PASSWORD_HASH);
    endUser.setRegistrationTimestamp(TEST_REGISTRATION_TIMESTAMP);
    try {
        endUser.setEmailAddress(new InternetAddress(TEST_EMAIL_ADDRESS_AS_STRING));
    } catch (AddressException e) {
        throw new RuntimeException(e);
    }

    return endUser;
}

From source file:mx.unam.pixel.controller.MailController.java

public void enviaMensaje(String mensaje) {
    try {/*w w w .j  a  v  a 2s.  c  o  m*/
        Properties props = new Properties();

        // Nombre del host de correo, es smtp.gmail.com
        props.setProperty("mail.smtp.host", "smtp.gmail.com");

        // TLS si est disponible
        props.setProperty("mail.smtp.starttls.enable", "true");

        // Puerto de gmail para envio de correos
        props.setProperty("mail.smtp.port", "587");

        // Nombre del usuario
        props.setProperty("mail.smtp.user", "ejemplo@gmail.com");

        // Si requiere o no usuario y password para conectarse.
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);
        //session.setDebug(true);

        //Construimos el mensage
        MimeMessage message = new MimeMessage(session);
        InternetAddress cuenta = new InternetAddress("enrique.wps@gmail.com");
        message.setFrom(); //Correo electronico que manda el mensaja
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("vampa@ciencias.unam.mx"));
        message.setSubject("Test MUFFIN");
        message.setText("Test Muffin Cuerpo");
        // Abrimos la comunicacion 
        Transport t = session.getTransport("smtp");

        t.connect("dasds@gmail.com", "asdsadas"); // Ususario y contrasea
        t.sendMessage(message, message.getAllRecipients());
        // Cierre
        t.close();

    } catch (AddressException ex) {
        System.err.println("er");
    } catch (MessagingException ex) {
        Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.szmslab.quickjavamail.utils.MailAddress.java

/**
 * InternetAddress?????/*ww w.j a v  a  2 s.  co  m*/
 *
 * @param charset
 *            
 * @return InternetAddress?
 * @throws AddressException
 * @throws UnsupportedEncodingException
 */
public InternetAddress toInternetAddress(String charset) throws AddressException, UnsupportedEncodingException {
    if (StringUtils.isBlank(personal)) {
        return new InternetAddress(address);
    } else {
        return new InternetAddress(address, personal, charset);
    }
}

From source file:net.kamhon.ieagle.function.email.SendMail.java

public void send(String to, String cc, String bcc, String from, String subject, String text, String emailType) {

    // Session session = Session.getInstance(props, null);
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailServerSetting.getUsername(),
                    emailServerSetting.getPassword());
        }/*from w w  w . j av a2 s  .  com*/
    });

    session.setDebug(emailServerSetting.isDebug());

    try {
        Message msg = new MimeMessage(session);
        if (StringUtils.isNotBlank(from)) {
            msg.setFrom(new InternetAddress(from));
        } else {
            msg.setFrom();
        }

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (StringUtils.isNotBlank(cc)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if (StringUtils.isNotBlank(bcc)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        msg.setSubject(subject);
        if (Emailq.TYPE_HTML.equalsIgnoreCase(emailType)) {
            msg.setContent(text, "text/html");
        } else {
            msg.setText(text);
        }
        msg.setSentDate(new java.util.Date());
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        throw new SystemErrorException(mex);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaEmailImp.java

@Override
public void enviarAlerta(List<AlertaServicio> alertas) {
    try {/*from  w  w w . j a v  a 2  s. c  o  m*/
        for (AlertaServicio x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta");
            ST contenido = new ST(contenidoRaw);
            contenido.add("cliente", x.getNombreCliente());
            contenido.add("tipo", x.getTipoAuto());
            contenido.add("marca", x.getMarcaAuto());
            contenido.add("placas", x.getPlacasAuto());
            contenido.add("kilometraje", x.getKilometrajeAuto());
            contenido.add("servicio", x.getDescripcionServicio());
            contenido.add("kilometrajeServicio", x.getKilometrajeServicio());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ning.metrics.meteo.publishers.AlertListener.java

private void createAndSendAlertEmail(String body) {
    try {//from  w  w w . ja  v a  2s. c om
        log.info(String.format("Sending alert email to [%s]: %s", config.getRecipients(), body));

        HtmlEmail email = new HtmlEmail();

        email.setTextMsg(body);
        email.setFrom("esper-is-awesome@example.com");
        email.setTo(Arrays.asList(new InternetAddress(config.getRecipients())));
        email.setHostName(config.getHost());
        email.setSmtpPort(config.getPort());
        email.send();
    } catch (Exception ex) {
        log.warn("Could not create or send email", ex);
    }
}

From source file:cdr.forms.DepositValidator.java

@Override
public void validate(Object target, Errors errors) {

    Deposit deposit = (Deposit) target;//from www  .  ja  va  2 s .  com
    Form form = deposit.getForm();

    // Validate receipt email address

    if (deposit.getReceiptEmailAddress() != null && deposit.getReceiptEmailAddress().trim().length() > 0) {
        try {
            InternetAddress address = new InternetAddress(deposit.getReceiptEmailAddress());
            address.validate();
        } catch (AddressException e) {
            errors.rejectValue("receiptEmailAddress", "invalidEmailAddress",
                    "You must enter a valid email address.");
        }
    }

    // The main file is required if there are no FileBlock elements

    if (!form.isHasFileBlocks()) {
        if (deposit.getMainFile() == null)
            errors.rejectValue("mainFile", "file.required", "This file is required.");
    }

    // Validate the form

    int elementIndex = 0;

    for (DepositElement element : deposit.getElements()) {

        if (element.getFormElement() instanceof MetadataBlock) {

            int entryIndex = 0;

            MetadataBlock metadataBlock = (MetadataBlock) element.getFormElement();

            for (DepositEntry entry : element.getEntries()) {

                int portIndex = 0;

                for (InputField<?> inputField : metadataBlock.getPorts()) {

                    if (inputField instanceof EmailInputField) {
                        String path = "elements[" + elementIndex + "].entries[" + entryIndex + "].fields["
                                + portIndex + "].value";

                        try {
                            InternetAddress address = new InternetAddress((String) errors.getFieldValue(path));
                            address.validate();
                        } catch (AddressException e) {
                            errors.rejectValue(path, "invalidEmailAddress",
                                    "You must enter a valid email address.");
                        }
                    } else if (inputField.isRequired()) {
                        String path = "elements[" + elementIndex + "].entries[" + entryIndex + "].fields["
                                + portIndex + "].value";
                        ValidationUtils.rejectIfEmptyOrWhitespace(errors, path, "field.required",
                                "This field is required.");
                    }

                    portIndex++;

                }

                entryIndex++;

            }

        }

        if (element.getFormElement() instanceof FileBlock) {

            int entryIndex = 0;

            FileBlock fileBlock = (FileBlock) element.getFormElement();

            for (DepositEntry entry : element.getEntries()) {

                if (fileBlock.isRequired() && entry.getFile() == null)
                    errors.rejectValue("elements[" + elementIndex + "].entries[" + entryIndex + "].file",
                            "file.required", "This file is required.");

                entryIndex++;

            }

        }

        if (element.getFormElement() instanceof MajorBlock) {

            MajorBlock majorBlock = (MajorBlock) element.getFormElement();

            if (majorBlock.getSelectedMajor() == null) {
                errors.rejectValue("elements[" + elementIndex + "]", "field.required",
                        "This field is required.");
            }

        }

        elementIndex++;

    }

}

From source file:se.vgregion.mobile.services.SmtpErrorReportService.java

@Override
public void report(ErrorReport report) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    try {//from   w  ww .  j  a v a 2  s  . c o m
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);

        String text = String.format(body, report.getPrinter().getName(), report.getDescription(),
                report.getReporter());
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("Failed sending error report via mail", e);
    }

}