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.dattack.dbtools.drules.engine.DefaultNotificationActionBeanVisitor.java

private void sendMail(final ConfigurationSmtpBean config, final NotificationActionSendMailBean action)
        throws EmailException, AddressException, ConfigurationException, TemplateException, IOException {

    if (config == null) {
        LOGGER.warn("Missing SMTP configuration. Please, check your configuration file.");
        return;//www.  ja va 2 s  . co m
    }

    final CompositeConfiguration configuration = new CompositeConfiguration();
    configuration.addConfiguration(ThreadContext.getInstance().getConfiguration());
    configuration.setDelimiterParsingDisabled(true);
    configuration.setProperty(PropertyNames.TASK_NAME, flightRecorder.getTaskBean().getName());
    configuration.setProperty(PropertyNames.LOG, flightRecorder.getReport().toString());
    configuration.setProperty(PropertyNames.SUCCESS_ROWS, flightRecorder.getSuccessCounter());
    configuration.setProperty(PropertyNames.ERROR_ROWS, flightRecorder.getErrorCounter());
    configuration.setProperty(PropertyNames.WARNING_ROWS, flightRecorder.getWarningCounter());

    for (final ConfigurationMailingListBean item : config.getMailingLists()) {
        configuration.setProperty(item.getName(), item.getAddressList());
    }

    final HtmlEmailBuilder htmlEmailBuilder = new HtmlEmailBuilder() //
            .withHostName(ConfigurationUtil.interpolate(config.getHostname(), configuration)) //
            .withPort(config.getPort()) //
            .withUsername(ConfigurationUtil.interpolate(config.getUsername(), configuration)) //
            .withPassword(ConfigurationUtil.interpolate(config.getPassword(), configuration)) //
            .withFrom(ConfigurationUtil.interpolate(config.getFrom(), configuration)) //
            .withSubject(ConfigurationUtil.interpolate(action.getSubject(), configuration)) //
            .withMessage(formatMessage(action, configuration)) //
            .withSslOnConnect(config.isSslOnConnect()) //
            .withStartTlsEnabled(config.isStartTlsEnabled()); //

    for (final String to : action.getToAddressesList()) {
        final String[] addresses = StringUtils.split(ConfigurationUtil.interpolate(to, configuration), " ,");
        for (final String item : addresses) {
            htmlEmailBuilder.withToAddress(new InternetAddress(item));
        }
    }

    htmlEmailBuilder.build().send();
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {/*  www.j ava2 s . c  o m*/
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:ua.aits.sdolyna.controller.MainController.java

@RequestMapping(value = { "/sendmail/", "/sendmail" }, method = RequestMethod.GET)
public @ResponseBody String sendMail(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String text = request.getParameter("text");
    final String username = "office@crc.org.ua";
    final String password = "crossroad2000";
    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 javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(username, password);
        }/*w w  w . j av  a2s  .c o  m*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sonyachna-dolyna@ukr.net"));
        message.setSubject("E-mail ? ?:");
        message.setText("?: " + name + "\nEmail: " + email + "\n\n" + text);
        Transport.send(message);
        return "done";
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Send mail to the given email id with the provided text and subject.
 * //from w  ww  .j av  a2s. c  o  m
 * @param recepientEmailId email id of the recepient
 * @param emailText text of the mail
 * @param subject subject of the mail
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 */
protected void sendMail(String recepientEmailId, String emailText, String subject)
        throws IdeasExchangeException, AddressException, MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    Message message = new MimeMessage(session);

    message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId));
    message.setFrom(new InternetAddress(getAdminMailId()));

    message.setText(emailText);
    message.setSubject(subject);

    Transport.send(message);
    log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject);
}

From source file:com.app.mail.DefaultMailSender.java

private static Message _populateContactMessage(String emailAddress, String messageBody, Session session)
        throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(emailAddress));

    message.addRecipient(Message.RecipientType.TO,
            new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS));

    message.setSubject("You Have A New Message From " + emailAddress);
    message.setText(messageBody);/*from w  w w. java 2s .co m*/

    return message;
}

From source file:info.raack.appliancedetection.common.email.SMTPEmailSender.java

public void sendGeneralEmail(String recipientEmail, String subject, String body) {
    Session session = Session.getDefaultInstance(emailProperties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   w  w  w.  j  ava  2s . c  om
    });

    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject(subject + (!environment.equals("prod") ? " [" + environment + "]" : ""));
        message.setText(body);
    } catch (Exception e) {
        throw new RuntimeException("Could not create message", e);
    }

    emailQueue.add(message);
}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override/*from ww w  .ja  va  2  s  .co  m*/
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

From source file:com.mycollab.core.utils.StringUtils.java

public static boolean isValidEmail(String value) {
    try {/* www .  j  a va  2 s  . c  om*/
        //
        // Create InternetAddress object and validated the supplied
        // address which is this case is an email address.
        InternetAddress internetAddress = new InternetAddress(value);
        internetAddress.validate();
        return true;
    } catch (AddressException e) {
        return false;
    }
}

From source file:com.aurel.track.item.SendItemEmailAction.java

@Override
public void prepare() throws Exception {
    locale = (Locale) session.get(Constants.LOCALE_KEY);
    personBean = (TPersonBean) session.get(Constants.USER_KEY);
    if (personBean == null) {
        return;//from  ww  w.  ja v a 2 s .c o  m
    }
    personID = personBean.getObjectID();
    workItemContext = ItemBL.editWorkItem(workItemID, personID, locale, true);
    projectBean = SendItemEmailBL.getProject(workItemContext.getWorkItemBean().getProjectID());
    fromAddressList = new ArrayList<LabelValueBean>();

    String userAddr = personBean.getEmail();
    LabelValueBean addres = new LabelValueBean();
    addres.setLabel(personBean.getFullName() + "<" + userAddr + ">");
    addres.setValue(userAddr);
    fromAddressList.add(addres);

    String defaultFrom = userAddr;

    String projectTrackSystemEmail = PropertiesHelper.getProperty(projectBean.getMoreProperties(),
            TProjectBean.MOREPPROPS.TRACK_EMAIL_PROPERTY);
    //String projectEmailPersonName=PropertiesHelper.getProperty(projectBean.getMoreProps(), TProjectBean.MOREPPROPS.EMAIL_PERSONAL_NAME);
    boolean useTrackFromAddressDisplay = "true".equalsIgnoreCase(PropertiesHelper.getProperty(
            projectBean.getMoreProperties(), TProjectBean.MOREPPROPS.USE_TRACK_FROM_ADDRESS_DISPLAY));
    String projectLocalized = projectBean.getLabel();// FieldRuntimeBL.getLocalizedDefaultFieldLabel(SystemFields.PROJECT, locale);
    if (projectTrackSystemEmail != null && projectTrackSystemEmail.length() > 0) {
        //verify address
        try {
            InternetAddress tmp = new InternetAddress(projectTrackSystemEmail);
            LOGGER.debug(tmp.getAddress() + " is valid!");
            addres = new LabelValueBean();
            addres.setLabel(projectLocalized + "<" + projectTrackSystemEmail + ">");
            addres.setValue(projectTrackSystemEmail);
            fromAddressList.add(addres);
            if (useTrackFromAddressDisplay) {
                defaultFrom = projectTrackSystemEmail;
            }
        } catch (AddressException e) {
            LOGGER.error("The email:'" + projectTrackSystemEmail + "' set on this project is invalid!");
        }
    }
    String emailAddress = ApplicationBean.getInstance().getSiteBean().getSendFrom().getEmail();
    if (emailAddress != null) {
        addres = new LabelValueBean();
        addres.setLabel(ApplicationBean.getInstance().getSiteBean().getSendFrom().getFullName() + "<"
                + emailAddress + ">");
        addres.setValue(emailAddress);
        fromAddressList.add(addres);

        if (!useTrackFromAddressDisplay && ApplicationBean.getInstance().getSiteBean()
                .getUseTrackFromAddressDisplay().equals(TSiteBean.SEND_FROM_MODE.SYSTEM)) {
            defaultFrom = emailAddress;
        }
    }
    if (from == null) {
        from = defaultFrom;
    }
    submitterEmail = workItemContext.getWorkItemBean().getSubmitterEmail();
    attachmentsList = new ArrayList<IntegerStringBean>();
    List attachListDB = null;
    if (workItemID == null) {
        attachListDB = workItemContext.getAttachmentsList();
    } else {
        attachListDB = AttachBL.getAttachments(workItemID);
    }
    if (attachListDB != null) {
        for (int i = 0; i < attachListDB.size(); i++) {
            TAttachmentBean attachmentBean = (TAttachmentBean) attachListDB.get(i);
            attachmentsList
                    .add(new IntegerStringBean(attachmentBean.getFileName(), attachmentBean.getObjectID()));
        }
    }
    String part0 = SendItemEmailBL.getMarker(workItemContext.getWorkItemBean(), locale);
    /*String part0 = LocalizeUtil.getParametrizedString("item.mail.subjectStructure.part0",
       new Object[] {workItemID}, locale);*/
    subjectReadolnyPart = part0 + "[" + projectBean.getLabel() + "]";
}

From source file:immf.ImodeMail.java

public InternetAddress getMyInternetAddress() {
    try {/*from   ww w .j  av  a 2 s .  co  m*/
        return new InternetAddress(this.getMyMailAddr());
    } catch (Exception e) {
        log.error("getMyInternetAddress Error." + this.getMyMailAddr(), e);
        return null;
    }
}