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, String personal) throws UnsupportedEncodingException 

Source Link

Document

Construct an InternetAddress given the address and personal name.

Usage

From source file:it.infn.ct.security.actions.ExtendAccount.java

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*from ww  w. j a  v a2  s  . c om*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:ninja.pif.simpleshop.controller.PortletViewController.java

@ActionMapping(params = "action=addBill")
public void updateEmployerCategory(ActionRequest actionRequest, ActionResponse actionResponse,
        @ModelAttribute(value = "bill") Bill bill, BindingResult bindingResult) {

    String nonce = ParamUtil.getString(actionRequest, "payment_method_nonce");
    billService.add(bill);//w w w . j  av a  2 s  .  c  o  m

    log.info("nonce " + nonce);

    //      TransactionRequest transactionRequest = new TransactionRequest()
    //       .amount(new BigDecimal("100.00"))
    //       .paymentMethodNonce(nonce);
    //      
    //      
    //
    //      Result<Transaction> result = new BraintreeGateway(
    //           Environment.SANDBOX,
    //           BraintreeConstants.MERCHAND_ID,
    //           BraintreeConstants.PUBLIC_KEY,
    //           BraintreeConstants.PRIVATE_KEY
    //         ).transaction().sale(transactionRequest);
    //      
    //      log.info("result.isSuccess()" + result.isSuccess());

    String location = actionRequest.getPortletSession().getPortletContext().getRealPath("")
            + "/WEB-INF/classes";

    String templateBodyCustomer = location + "/mail-to-customer.mustache";
    String templateBodyExpeditor = location + "/mail-to-expeditor.mustache";

    try {
        String mailBodyCustomer = Mustache.compiler().compile(new FileReader(templateBodyCustomer))
                .execute(bill);

        String mailBodyExpeditor = Mustache.compiler().compile(new FileReader(templateBodyExpeditor))
                .execute(bill);

        log.info("mailBodyCustomer : " + mailBodyCustomer);
        log.info("mailBodyExpeditor : " + mailBodyExpeditor);

        String subject = "Commande numro " + bill.getCommandeId() + " sur albert-gabrieleff.com";
        InternetAddress from;
        try {
            from = new InternetAddress(MailConstants.ADDRESS_NO_REPLY, MailConstants.NAME_NO_REPLY);

            //for the customer 
            InternetAddress to = new InternetAddress(bill.getFacurationAddress().getEmail(),
                    bill.getFacurationAddress().getName());
            MailMessage mailMessage = new MailMessage(from, to, subject, mailBodyCustomer, false);
            MailServiceUtil.sendEmail(mailMessage);

            //for the expeditor
            to = new InternetAddress(MailConstants.ADDRESS_EXPEDITOR, MailConstants.NAME_EXPEDITOR);
            mailMessage = new MailMessage(from, to, subject, mailBodyExpeditor, false);
            mailMessage.setCC(
                    new InternetAddress(MailConstants.ADDRESS_CC_EXPEDITOR, MailConstants.NAME_CC_EXPEDITOR));
            MailServiceUtil.sendEmail(mailMessage);

        } catch (UnsupportedEncodingException e) {
            log.error(e);
        }

    } catch (FileNotFoundException e1) {
        log.error("file not found");
    }

}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessageTest.java

public static Email getSimpleMail() throws UnsupportedEncodingException {
    return getSimpleMail(new InternetAddress("cicero@mala-tempora.currunt", "Marco Tullio Cicerone"));
}

From source file:it.infn.ct.security.actions.ReactivateUser.java

private void sendMail(LDAPUser user) throws MailException {
    javax.mail.Session session = null;/*from w w w.j a  va  2  s  .c o  m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

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

/**
 * Checks whether the given email address is a valid email address using strict checks
 * @param email/* w w  w.  j  a v a 2s .  c  o m*/
 * @return email address if email is valid, null if email is invalid
 */
public static String validate(String email) {
    /* email size must be smaller than max domain + max local */
    if (email != null && email.length() < (255 + 65)) {
        try {
            InternetAddress validated = new InternetAddress(email, true /* strict checking */);

            return validated.getAddress();
        } catch (AddressException ignored) {
            logger.debug("Email address \"{}\" is not a valid email address", email);
        }
    }
    return null;
}

From source file:com.youxifan.utils.EMail.java

/**
 *  Add To Recipient// www  . j  a v  a  2s  . c  o m
 *  @param newToEMail Recipient's email address
 *    @return true if valid
 */
public boolean addTo(String newToEMail, String newToName) {
    if (newToEMail == null || newToEMail.length() == 0) {
        m_valid = false;
        return m_valid;
    }
    InternetAddress ia = null;
    try {
        if (newToName == null)
            ia = new InternetAddress(newToEMail, true);
        else
            ia = new InternetAddress(newToEMail, newToName);
    } catch (Exception e) {
        log.error(newToEMail + ": " + e.toString());
        m_valid = false;
        return m_valid;
    }
    if (m_to == null)
        m_to = new ArrayList<InternetAddress>();
    m_to.add(ia);
    return m_valid;
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!/*from   www . jav a2 s  .  c  o  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.rodaxsoft.mailgun.ListMember.java

/**
 * Return a String representation of this address object.
 *//*from   w  w w .j  a  v a  2s . c  o m*/
@Override
public String toString() {
    if (address != null) {
        try {
            return new InternetAddress(address, name).toString();
        } catch (UnsupportedEncodingException e) {
            throw new ContextedRuntimeException(e);
        }
    }

    else {
        return null;
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*from w w w .  j  a va  2 s.  c om*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:org.zanata.sync.jobs.system.ResourceProducer.java

@Produces
protected Address systemNotificationEmailAddress() {
    String email = System.getProperty(SYSTEM_NOTIFICATION_EMAIL);
    if (!Strings.isNullOrEmpty(email)) {
        try {//from  w  ww  . j  av  a2s. c  om
            return new InternetAddress(email, "Zanata Sync System");
        } catch (UnsupportedEncodingException e) {
            throw Throwables.propagate(e);
        }
    }
    throw new IllegalStateException(SYSTEM_NOTIFICATION_EMAIL + " system property is not set");
}