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:dk.teachus.backend.bean.impl.TestSpringMailBean.java

public void testSendMail() throws Exception {
    MailBean mailBean = createMailBean();

    mailBean.sendMail(new InternetAddress("test@teachus.dk"), new InternetAddress("test2@teachus.dk"),
            "A subject", "A body", MailMessage.Type.PLAIN);
}

From source file:gov.nih.nci.caintegrator.application.mail.SendMail.java

public synchronized void sendMail(String mailTo, String mailCC, String mailBody, String subject)
        throws ValidationException {
    try {/*  ww  w.jav a  2  s. com*/
        if (mailTo != null && EmailValidator.getInstance().isValid(mailTo)) {
            //get system properties
            Properties props = System.getProperties();

            String to = mailTo;
            // Set up mail server

            props.put("mail.smtp.host", MailConfig.getInstance(mailProperties).getHost());

            //Get session
            Session session = Session.getDefaultInstance(props, null);

            //Define Message
            MimeMessage message = new MimeMessage(session);
            MailManager mailManager = new MailManager(mailProperties);
            message.setFrom(new InternetAddress(mailManager.formatFromAddress()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if ((mailCC != null) && EmailValidator.getInstance().isValid(mailCC))
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCC));
            message.setSubject(subject);
            message.setText(mailBody);

            //Send Message

            Transport.send(message);
        } else {
            throw new ValidationException("Invalid Email Address");
        }
    } catch (Exception e) {
        logger.error("Send Mail error", e);
    } //catch
}

From source file:com.sun.socialsite.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*from  ww  w.  j av  a 2s .  co  m*/
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Startup.getMailProvider().getTransport().sendMessage(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from   w w w. jav  a2s  . c om
 *
 * @param from     e-mail address of sender
 * @param to       e-mail address(es) of recipients
 * @param subject  subject of e-mail
 * @param content  the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled()) {
            mLogger.debug("e-mail from: " + sentFrom);
        }
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("sending e-mail to: " + to[i]);
            }
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("copying e-mail to: " + cc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome) {
        throw sendex;
    }
}

From source file:SendMailImpl.java

public void sendMessage(String from, String[] recipients, String subject, String message)
        throws MessagingException {
    boolean debug = false;

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);/*w w  w .  j  av a2s  . com*/

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
}

From source file:com.bizintelapps.cars.service.impl.EmailServiceImpl.java

/**
 * /*from  w  w  w . j a  va  2s.c  o  m*/
 * @param recipients
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, Car car, String comment) {

    try {
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {

                addressTo[i] = new InternetAddress(recipients[i]);

            }
        }

        if (addressTo == null || addressTo.length == 0) {
            return;
        }

        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_FROM_USERNAME, SEND_FROM_PASSWORD);
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(EMAIL_FROM_ADDRESS);
        msg.setFrom(addressFrom);
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        String message = buildMessage(car, comment);
        msg.setContent(message, EMAIL_CONTENT_TYPE);

        Transport.send(msg);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Error sending email, please check to and from emails are correct!");
    }
}

From source file:com.jaspersoft.jasperserver.core.util.validators.EmailInputValidator.java

@Override
public boolean isValid(T email) {
    if (email == null) {
        return false;
    }/*  w  ww.  j a v a  2s  . c  om*/

    if (this.getPattern() != null) {
        return super.isValid(email);

    } else {
        boolean result = true;
        try {
            InternetAddress emailAddress = new InternetAddress(email.toString());
            emailAddress.validate();
        } catch (AddressException ex) {
            result = false;
            if (log.isDebugEnabled()) {
                log.debug(String.format("Email address %s not valid.", email));
            }
        }

        return result;
    }
}

From source file:com.liferay.util.mail.MailEngine.java

public static void send(String from, String to, String subject, String body) throws MailEngineException {

    try {//from  w  ww  .  ja v  a 2 s  .  c  o  m
        send(new InternetAddress(from), new InternetAddress(to), subject, body);
    } catch (AddressException ae) {
        throw new MailEngineException(ae);
    }
}

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

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

    systemService.requestNewDiseaseGroup("newDisease", "sender1", UserType.D);

    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(new InternetAddress("sender1"), messages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("mitglied@projecth.com"),
            messages.get(0).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("Neue Gesundheitsgruppe anmelden: newDisease", messages.get(0).getMimeMessage().getSubject());

    assertEquals(new InternetAddress("gesundheitsgruppen@projecth.com"),
            messages.get(1).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("sender1"),
            messages.get(1).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("Anfrage zur Erweiterung von projecth mit newDisease",
            messages.get(1).getMimeMessage().getSubject());
}

From source file:easyproject.utils.SendMail.java

@Override
public void run() {

    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {//from  w  w  w  .  j a va 2  s . c om
        MimeMessage message1 = new MimeMessage(session);

        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message1.setSubject(asunto);
        message1.setSentDate(new Date());
        message1.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message1.saveChanges();
        tr.sendMessage(message1, message1.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }

}