Example usage for org.springframework.mail.javamail JavaMailSenderImpl send

List of usage examples for org.springframework.mail.javamail JavaMailSenderImpl send

Introduction

In this page you can find the example usage for org.springframework.mail.javamail JavaMailSenderImpl send.

Prototype

@Override
    public void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException 

Source Link

Usage

From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTPSpring.java

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);/*from  w  w  w . j a va  2 s. c o  m*/
    TextField smtpPort = new TextField("SMTP Port");
    smtpPort.setRequired(true);
    TextField smtpUser = new TextField("SMTP Username");
    smtpUser.setRequired(true);
    PasswordField smtpPwd = new PasswordField("SMTP Password");
    smtpPwd.setRequired(true);
    PasswordField pwdConf = new PasswordField("Conferma la Password");
    pwdConf.setRequired(true);
    CheckBox security = new CheckBox("Sicurezza del server");

    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        System.out.println("Carico file di configurazione");
        try {
            props.load(config);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    smtpHost.setValue(props.getProperty("mail.smtp.host"));
    smtpUser.setValue(props.getProperty("smtp_user"));
    security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec")));

    Button salva = new Button("Salva i parametri");
    salva.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Salvo i parametri SMTP");
        if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid()
                && smtpPwd.getValue().equals(pwdConf.getValue())) {
            System.out.println(smtpHost.getValue() + smtpPort.getValue() + smtpUser.getValue()
                    + smtpPwd.getValue() + security.getValue().toString());
            props.setProperty("mail.smtp.host", smtpHost.getValue());
            props.setProperty("mail.smtp.port", smtpPort.getValue());
            props.setProperty("smtp_user", smtpUser.getValue());
            props.setProperty("smtp_pwd", smtpPwd.getValue());
            props.setProperty("mail.smtp.ssl.enable", security.getValue().toString());
            String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext()
                    .getRealPath("WEB-INF");
            File f = new File(webInfPath + "/config.properties");
            try {
                OutputStream o = new FileOutputStream(f);
                try {
                    props.store(o, "Prova");
                } catch (IOException ex) {
                    Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            Notification.show("Parametri salvati");
        } else {
            Notification.show("Ricontrolla i parametri");
        }

    });

    TextField emailTest = new TextField("Destinatario Mail di Prova");
    emailTest.setImmediate(true);
    emailTest.addValidator(new EmailValidator("Mail non valida"));

    Button test = new Button("Invia una mail di prova");
    test.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Invio della mail di prova");
        if (emailTest.isValid() && !emailTest.isEmpty()) {
            System.out.println("Invio mail di prova a " + emailTest.getValue());
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setJavaMailProperties(props);
            mailSender.setUsername(props.getProperty("smtp_user"));
            mailSender.setPassword(props.getProperty("smtp_pwd"));
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            try {
                helper.setFrom("dottmatteocasagrande@gmail.com");
                helper.setSubject("Subject");
                helper.setText("It works!");
                helper.addTo(emailTest.getValue());
                mailSender.send(message);
            } catch (MessagingException ex) {
                Logger.getLogger(ConfigurazioneSMTPSpring.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            Notification.show("Controlla l'indirizzo mail del destinatario");
        }
    });

    this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test);

}

From source file:com.springsource.insight.plugin.mail.MessageSendOperationCollectionAspectTest.java

private void testSendMessage(int port) {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(NetworkAddressUtil.LOOPBACK_ADDRESS);
    sender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
    sender.setPort(port);/*from  w  w  w. j a  va2s.  c om*/

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("from@com.springsource.insight.plugin.mail");
    message.setTo("to@com.springsource.insight.plugin.mail");
    message.setCc("cc@com.springsource.insight.plugin.mail");
    message.setBcc("bcc@com.springsource.insight.plugin.mail");

    Date now = new Date(System.currentTimeMillis());
    message.setSentDate(now);
    message.setSubject(now.toString());
    message.setText("Test at " + now.toString());
    sender.send(message);

    Operation op = getLastEntered();
    assertNotNull("No operation extracted", op);
    assertEquals("Mismatched operation type", MailDefinitions.SEND_OPERATION, op.getType());
    assertEquals("Mismatched protocol", sender.getProtocol(),
            op.get(MailDefinitions.SEND_PROTOCOL, String.class));
    assertEquals("Mismatched host", sender.getHost(), op.get(MailDefinitions.SEND_HOST, String.class));
    if (port == -1) {
        assertEquals("Mismatched default port", 25, op.getInt(MailDefinitions.SEND_PORT, (-1)));
    } else {
        assertEquals("Mismatched send port", sender.getPort(), op.getInt(MailDefinitions.SEND_PORT, (-1)));
    }

    if (getAspect().collectExtraInformation()) {
        assertAddresses(op, MailDefinitions.SEND_SENDERS, 1);
        assertAddresses(op, MailDefinitions.SEND_RECIPS, 3);

        OperationMap details = op.get(MailDefinitions.SEND_DETAILS, OperationMap.class);
        assertNotNull("No details extracted", details);
        assertEquals("Mismatched subject", message.getSubject(),
                details.get(MailDefinitions.SEND_SUBJECT, String.class));
    }
}

From source file:org.brushingbits.jnap.email.EmailSender.java

public void send(Email email) {
    EmailAccountInfo accountInfo = defaultEmailAccount;
    JavaMailSenderImpl sender = this.defaultMailSender;
    if (email.getAccountInfo() != null) {
        accountInfo = email.getAccountInfo();
        synchronized (this.mailSenderMap) {
            sender = this.mailSenderMap.get(accountInfo);
            if (sender == null) {
                sender = new JavaMailSenderImpl();
                Properties props = new Properties(this.defaultEmailAccount.getJavaMailProperties());
                props.putAll(accountInfo.getJavaMailProperties());
                sender.setJavaMailProperties(props);
                sender.setUsername(accountInfo.getUsername());
                sender.setPassword(accountInfo.getPassword());
                this.mailSenderMap.put(accountInfo, sender);
            }/*from  w ww.  j  a  v  a2 s.  c  om*/
        }
    }
    sender.send((MimeMessagePreparator) email);
}

From source file:org.tsm.concharto.lab.LabJavaMail.java

private void sendConfirmationEmail(User user) {
    //mailSender.setHost("skipper");
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getEmail());/*from w ww .  j a  v a2 s.c om*/
    String messageText = StringUtils.replace(WELCOME_MESSAGE, PARAM_NAME, user.getUsername());
    message.setText(messageText);
    message.setSubject(WELCOME_SUBJECT);
    message.setFrom("<Concharto Notifications> notify@concharto.com");

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    InternetAddress from = new InternetAddress();
    from.setAddress("notify@concharto.com");
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal("Concharto Notifications");
        mimeMessage.addRecipient(Message.RecipientType.TO, to);
        mimeMessage.setSubject(WELCOME_SUBJECT);
        mimeMessage.setText(messageText);
        mimeMessage.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mailSender.setHost("localhost");
    mailSender.send(mimeMessage);

    /*
    Confirm your registration with Concharto
            
    Hello sanmi,
            
    Welcome to the Concharto community!
            
    Please click on this link to confirm your registration: http://www.concharto.com/member/confirm.htm?id=:confirmation 
            
    You can find out more about us at http://wiki.concharto.com/wiki/About.
            
    If you were not expecting this email, just ignore it, no further action is required to terminate the request.
     */
}

From source file:org.jnap.core.email.EmailSender.java

public void send(Email email) {
    EmailAccountInfo accountInfo = defaultEmailAccount;
    JavaMailSenderImpl sender = this.defaultMailSender;
    if (email.getAccountInfo() != null) {
        accountInfo = email.getAccountInfo();
        synchronized (this.mailSenderMap) {
            sender = this.mailSenderMap.get(accountInfo);
            if (sender == null) {
                sender = new JavaMailSenderImpl();
                Properties props = new Properties(this.defaultEmailAccount.getJavaMailProperties());
                props.putAll(accountInfo.getJavaMailProperties());
                sender.setJavaMailProperties(props);
                sender.setUsername(accountInfo.getUsername());
                sender.setPassword(accountInfo.getPassword());
                this.mailSenderMap.put(accountInfo, sender);
            }/*from w  w  w .j  a v  a 2 s . com*/
        }
    } else {
        email.setAccountInfo(accountInfo);
    }
    sender.send((MimeMessagePreparator) email);
}

From source file:org.syncope.core.scheduling.NotificationJob.java

public TaskExec executeSingle(final NotificationTask task) {
    init();//from   w w  w .  j a  v a  2 s  .  c  o  m

    TaskExec execution = new TaskExec();
    execution.setTask(task);
    execution.setStartDate(new Date());

    if (StringUtils.isBlank(smtpHost) || StringUtils.isBlank(task.getSender())
            || StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for " + "sending e-mails:\n" + smtpHost + ":"
                + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject()
                + "\n" + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(Status.NOT_SENT.name());

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {

            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients()
                    + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n"
                    + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                JavaMailSenderImpl sender = new JavaMailSenderImpl();
                sender.setHost(smtpHost);
                sender.setPort(smtpPort);
                if (StringUtils.isNotBlank(smtpUsername)) {
                    sender.setUsername(smtpUsername);
                }
                if (StringUtils.isNotBlank(smtpPassword)) {
                    sender.setPassword(smtpPassword);
                }

                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);

                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                sender.send(message);

                execution.setStatus(Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }
            } catch (Throwable t) {
                LOG.error("Could not send e-mail", t);

                execution.setStatus(Status.NOT_SENT.name());
                StringWriter exceptionWriter = new StringWriter();
                exceptionWriter.write(t.getMessage() + "\n\n");
                t.printStackTrace(new PrintWriter(exceptionWriter));

                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {

                    execution.setMessage(exceptionWriter.toString());
                }
            }

            execution.setEndDate(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = taskExecDAO.save(execution);
    }

    return execution;
}

From source file:nz.net.orcon.kanban.automation.actions.EmailSenderAction.java

public void sendSecureEmail(String subject, String emailBody, String to, String bcc, String from,
        String replyTo, String host, String password) {

    SimpleMailMessage mailMessage = new SimpleMailMessage();
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

    mailSender.setHost(host);/*from  w  w  w . jav a 2s  .co m*/
    mailSender.setPort(587);
    mailSender.setProtocol("smtp");

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");

    mailSender.setJavaMailProperties(props);

    if (StringUtils.isNotBlank(to)) {
        mailMessage.setTo(to);
    }
    if (StringUtils.isNotBlank(bcc)) {
        mailMessage.setBcc(bcc);
    }

    if (StringUtils.isNotBlank(from)) {
        mailMessage.setFrom(from);
        mailSender.setUsername(from);
    }

    if (StringUtils.isNotBlank(password)) {
        mailSender.setPassword(password);
    }

    if (StringUtils.isNotBlank(replyTo)) {
        mailMessage.setReplyTo(replyTo);
    }

    if (StringUtils.isNotBlank(subject)) {
        mailMessage.setSubject(subject);
    }

    mailMessage.setText(emailBody);
    mailSender.send(mailMessage);
    logger.info("Secure Email Message has been sent..");
}

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {/*w  ww .j a  va2s . c o  m*/
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getGmailSmtpServer());
        javaMailSenderImpl.setPort(this.getGmailSmtpPort());
        javaMailSenderImpl.setUsername(this.getGmailSmtpUsername());
        javaMailSenderImpl.setPassword(this.getGmailSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}

From source file:uk.ac.gda.dls.client.feedback.FeedbackDialog.java

@Override
protected void createButtonsForButtonBar(Composite parent) {

    GridData data = new GridData(SWT.FILL, SWT.FILL, false, true, 4, 1);
    GridLayout layout = new GridLayout(5, false);
    parent.setLayoutData(data);//  w w w. j  ava2  s  .co  m
    parent.setLayout(layout);

    Button attachButton = new Button(parent, SWT.TOGGLE);
    attachButton.setText("Attach File(s)");
    attachButton.setToolTipText("Add files to feedback");

    final Button screenGrabButton = new Button(parent, SWT.CHECK);
    screenGrabButton.setText("Include Screenshot");
    screenGrabButton.setToolTipText("Send screenshot with feedback");

    Label space = new Label(parent, SWT.NONE);
    space.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

    Button sendButton = new Button(parent, SWT.PUSH);
    sendButton.setText("Send");

    Button cancelButton = new Button(parent, SWT.PUSH);
    cancelButton.setText("Cancel");

    sendButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {

            final String name = nameText.getText();
            final String email = emailText.getText();
            final String subject = subjectText.getText();
            final String description = descriptionText.getText();

            fileList = attachedFileList.getItems();

            Job job = new Job("Send feedback email") {
                @Override
                protected IStatus run(IProgressMonitor monitor) {

                    try {
                        final String recipientsProperty = LocalProperties.get("gda.feedback.recipients",
                                "dag-group@diamond.ac.uk");
                        final String[] recipients = recipientsProperty.split(" ");
                        for (int i = 0; i < recipients.length; i++) {
                            recipients[i] = recipients[i].trim();
                        }

                        final String from = String.format("%s <%s>", name, email);

                        final String beamlineName = LocalProperties.get("gda.beamline.name",
                                "Beamline Unknown");
                        final String mailSubject = String.format("[GDA feedback - %s] %s",
                                beamlineName.toUpperCase(), subject);

                        final String smtpHost = LocalProperties.get("gda.feedback.smtp.host", "localhost");

                        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
                        mailSender.setHost(smtpHost);

                        MimeMessage message = mailSender.createMimeMessage();
                        final MimeMessageHelper helper = new MimeMessageHelper(message,
                                (FeedbackDialog.this.hasFiles && fileList.length > 0)
                                        || FeedbackDialog.this.screenshot);
                        helper.setFrom(from);
                        helper.setTo(recipients);
                        helper.setSubject(mailSubject);
                        helper.setText(description);

                        if (FeedbackDialog.this.screenshot) {
                            PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                                @Override
                                public void run() {
                                    String fileName = "/tmp/feedbackScreenshot.png";
                                    try {
                                        captureScreen(fileName);
                                        FileSystemResource file = new FileSystemResource(new File(fileName));
                                        helper.addAttachment(file.getFilename(), file);
                                    } catch (Exception e) {
                                        logger.error("Could not attach screenshot to feedback", e);
                                    }
                                }
                            });
                        }

                        if (FeedbackDialog.this.hasFiles) {
                            for (String fileName : fileList) {
                                FileSystemResource file = new FileSystemResource(new File(fileName));
                                helper.addAttachment(file.getFilename(), file);
                            }
                        }

                        {//required to workaround class loader issue with "no object DCH..." error
                            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                            mc.addMailcap(
                                    "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                            mc.addMailcap(
                                    "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                            CommandMap.setDefaultCommandMap(mc);
                        }
                        mailSender.send(message);
                        return Status.OK_STATUS;
                    } catch (Exception ex) {
                        logger.error("Could not send feedback", ex);
                        return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 1, "Error sending email", ex);
                    }

                }
            };

            job.schedule();

            setReturnCode(OK);
            close();
        }
    });

    cancelButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            setReturnCode(CANCEL);
            close();
        }
    });

    attachButton.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            hasFiles = !hasFiles;
            GridData data = ((GridData) attachments.getLayoutData());
            data.exclude = !hasFiles;
            attachments.setVisible(hasFiles);
            topParent.layout();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });

    screenGrabButton.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            screenshot = ((Button) e.widget).getSelection();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
}

From source file:org.akaza.openclinica.control.core.SecureController.java

License:asdf

public Boolean sendEmail(String to, String from, String subject, String body, Boolean htmlEmail,
        String successMessage, String failMessage, Boolean sendMessage) throws Exception {
    Boolean messageSent = true;//from w  w w  .  j  a va2  s  .c om
    try {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) SpringServletAccess.getApplicationContext(context)
                .getBean("mailSender");
        // @pgawade 09-Feb-2012 #issue 13201 - setting the "mail.smtp.localhost" property to localhost when java API
        // is not able to
        // retrieve the host name
        Properties javaMailProperties = mailSender.getJavaMailProperties();
        if (null != javaMailProperties) {
            if (javaMailProperties.get("mail.smtp.localhost") == null
                    || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) {
                javaMailProperties.put("mail.smtp.localhost", "localhost");
            }
        }

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail);
        helper.setFrom(from);
        helper.setTo(processMultipleImailAddresses(to.trim()));
        helper.setSubject(subject);
        helper.setText(body, true);

        mailSender.send(mimeMessage);
        if (successMessage != null && sendMessage) {
            addPageMessage(successMessage);
        }
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        me.printStackTrace();
        if (failMessage != null && sendMessage) {
            addPageMessage(failMessage);
        }
        logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString());
        messageSent = false;
    }
    return messageSent;
}