Example usage for javax.mail.internet MimeMessage addRecipient

List of usage examples for javax.mail.internet MimeMessage addRecipient

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage addRecipient.

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:com.formkiq.core.service.notification.ExternalMailSender.java

/**
 * Send Reset Email./*from  w ww .j ava2  s.c  o  m*/
 * @param to {@link String}
 * @param email {@link String}
 * @param subject {@link String}
 * @param text {@link String}
 * @param html {@link String}
 * @throws MessagingException MessagingException
 */
private void sendResetEmail(final String to, final String email, final String subject, final String text,
        final String html) throws MessagingException {

    String hostname = this.systemProperties.getSystemHostname();
    String resetToken = this.userservice.generateResetToken(to);

    StringSubstitutor s = new StringSubstitutor(
            ImmutableMap.of("hostname", hostname, "to", to, "email", email, "resettoken", resetToken));

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(s.replace(text), "UTF-8");

    s.replace(html);
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(s.replace(html), "text/html;charset=UTF-8");

    final Multipart mp = new MimeMultipart("alternative");
    mp.addBodyPart(textPart);
    mp.addBodyPart(htmlPart);

    MimeMessage msg = this.mail.createMimeMessage();
    msg.setContent(mp);

    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    msg.setSubject(subject);

    this.mail.send(msg);
}

From source file:com.wso2telco.workflow.notification.EmailService.java

public void sendEmail(final String emailAddress, final String subject, final String content) {

    new Thread() {
        @Override/*from   w ww.jav a2 s. com*/
        public void run() {
            Map<String, String> workflowProperties = WorkflowProperties.loadWorkflowPropertiesFromXML();
            String emailHost = workflowProperties.get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST);
            String fromEmailAddress = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS);
            String fromEmailPassword = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD);

            Properties props = System.getProperties();
            props.put("mail.smtp.host", emailHost);
            props.put("mail.smtp.user", fromEmailAddress);
            props.put("mail.smtp.password", fromEmailPassword);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");

            try {
                Session session = Session.getDefaultInstance(props, null);
                InternetAddress toAddress = new InternetAddress(emailAddress);

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(fromEmailAddress));
                message.addRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subject);
                message.setContent(content, "text/html; charset=UTF-8");

                Transport transport = session.getTransport("smtp");
                transport.connect(emailHost, fromEmailAddress, fromEmailPassword);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

            } catch (Exception e) {
                log.error("Email sending failed. ", e);
            }
        }
    }.start();
}

From source file:org.mobicents.servlet.restcomm.email.EmailService.java

EmailResponse send(final Mail mail) {
    try {/*  w w  w .  j  a va  2 s.co m*/
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        Transport.send(email);
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:au.org.ala.biocache.service.EmailService.java

/**
 * Sends an email with the supplied details. 
 * //from  w ww  . j a v a 2 s. c o  m
 * @param recipient
 * @param subject
 * @param content
 * @param sender
 */
public void sendEmail(String recipient, String subject, String content, String sender) {

    logger.debug("Send email to : " + recipient);
    logger.debug("Body: " + content);
    Session session = Session.getDefaultInstance(properties);

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject);
        message.setContent(content, "text/html");
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Unable to send email to " + recipient + ".\n" + content, e);
    }
}

From source file:ru.org.linux.util.EmailService.java

public void sendEmail(String nick, String email, boolean isNew) throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {//from   w  w w .j a  v  a 2s . c  om
        text.append(
                "\t?   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t?   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(configuration.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}

From source file:com.twinsoft.convertigo.engine.admin.services.projects.Deploy.java

@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
    if (!item.getName().endsWith(".car")) {
        ServiceUtils/*ww w  . j  a v  a 2s .c om*/
                .addMessage(document, document.getDocumentElement(),
                        "The deployment of the project " + item.getName()
                                + " has failed. The archive file is not valid (.car required).",
                        "error", false);
    }

    super.doUpload(request, document, item);

    // Depending on client browsers, according to the documentation,
    // item.getName() can either return a full path file name, or
    // simply a file name.
    String projectArchive = item.getName();

    // Bugfix #1425
    int i = projectArchive.lastIndexOf('/');
    if (i == -1) {
        i = projectArchive.lastIndexOf('\\');
        if (i != -1) {
            projectArchive = projectArchive.substring(i + 1);
        }
    } else {
        projectArchive = projectArchive.substring(i + 1);
    }

    String projectName = projectArchive.substring(0, projectArchive.indexOf(".car"));

    Engine.theApp.databaseObjectsManager.deployProject(getRepository() + projectArchive, true, bAssembleXsl);

    if (Boolean.parseBoolean(
            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_NOTIFY_PROJECT_DEPLOYMENT))) {

        final String fUser = (String) request.getSession().getAttribute(SessionKey.ADMIN_USER.toString());
        final String fProjectName = projectName;

        new Thread(new Runnable() {
            public void run() {
                try {
                    Properties props = new Properties();

                    props.put("mail.smtp.host",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_HOST));
                    props.put("mail.smtp.socketFactory.port",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_PORT));
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.put("mail.smtp.socketFactory.fallback", "false");

                    // Initializing
                    Session mailSession = Session.getInstance(props, new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_USER),
                                    EnginePropertiesManager
                                            .getProperty(PropertyName.NOTIFICATIONS_SMTP_PASSWORD));
                        }
                    });
                    MimeMessage message = new MimeMessage(mailSession);

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_TARGET_EMAIL)));
                    message.setSubject("[trial] deployment of " + fProjectName + " by " + fUser);
                    message.setText(message.getSubject() + "\n" + "http://trial.convertigo.net/cems/projects/"
                            + fProjectName + "\n" + "https://trial.convertigo.net/cems/projects/"
                            + fProjectName);
                    Transport.send(message);
                } catch (MessagingException e1) {
                }
            }
        }).start();
    }

    String message = "The project '" + projectName + "' has been successfully deployed.";
    Engine.logAdmin.info(message);
    ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
}

From source file:org.tomitribe.tribestream.registryng.service.monitoring.MailAlerter.java

private void sendMail(final Alert alert) throws MessagingException {
    final String subject = StrSubstitutor.replace(subjectTemplate, new HashMap<String, String>() {
        {/*from www  .j  a va 2s  . com*/
            put("hostname", hostname);
            put("date", LocalDateTime.now().toString());
        }
    });
    final String body = alert.text();

    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();//from w w w. j  ava2s.c o  m
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {//from  w  ww. jav a 2  s . c o  m
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:org.codice.ddf.catalog.ui.query.monitor.email.EmailNotifier.java

private void sendEmailForWorkspace(WorkspaceMetacardImpl workspaceMetacard, Long hitCount, String email) {

    String emailBody = metacardFormatter.format(bodyTemplate, workspaceMetacard, hitCount);

    String subject = metacardFormatter.format(subjectTemplate, workspaceMetacard, hitCount);

    Session session = smtpClient.createSession();

    try {//  w ww .  jav a 2  s .  co m
        MimeMessage mimeMessage = new MimeMessage(session);

        mimeMessage.setFrom(new InternetAddress(fromEmail));

        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        mimeMessage.setSubject(subject);

        mimeMessage.setText(emailBody);

        LOGGER.trace("Attempting to send email");

        smtpClient.send(mimeMessage);

    } catch (MessagingException e) {
        LOGGER.warn("unable to send email to {}", email, e);
    }
}