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

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

Introduction

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

Prototype

@Override
public MimeMessage createMimeMessage() 

Source Link

Document

This implementation creates a SmartMimeMessage, holding the specified default encoding and default FileTypeMap.

Usage

From source file:com.mocktpo.util.EmailUtils.java

public static void sendActivationCode(License lic) {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(GlobalConstants.SMTP_HOST);
    sender.setUsername(GlobalConstants.SMTP_SENDER_EMAIL);
    sender.setPassword(GlobalConstants.SMTP_SENDER_PASSWORD);
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);
    try {//www.j  ava 2s  . c  om
        helper.setFrom(GlobalConstants.SMTP_SENDER_EMAIL);
        helper.setBcc(GlobalConstants.SMTP_SENDER_EMAIL);
        helper.setTo(lic.getEmail());
        helper.setSubject(GlobalConstants.LICENSE_EMAIL_SUBJECT);
        helper.setText(getActivationCode(lic));
    } catch (Exception e) {
        e.printStackTrace();
    }
    sender.send(message);
}

From source file:com.rxx.common.util.MailUtil.java

/**
 * html//from w w w.j a  va  2s. c om
 *
 * @param host 
 * @param port
 * @param userName
 * @param password
 * @param title
 * @param contenthtml
 * @param fileslist<Map<key:,value:>>
 * @param toUser
 * @throws javax.mail.MessagingException
 */
public static void sendAttached(String host, int port, String userName, String password, String title,
        String content, List<Map<String, String>> files, String[] toUser)
        throws MessagingException, javax.mail.MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

    // mail server
    senderImpl.setHost(host);
    // ,html
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // boolean,MimeMessageHelpertrue
    // multipart true html
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    // 
    messageHelper.setTo(toUser);
    messageHelper.setFrom(userName);
    messageHelper.setSubject(title);
    // true HTML
    messageHelper.setText(content, true);

    for (Map<String, String> filePath : files) {
        Iterator<String> it = filePath.keySet().iterator();
        String fileName = it.next();
        FileSystemResource file = new FileSystemResource(new File(filePath.get(fileName)));
        // 
        messageHelper.addAttachment(fileName, file);
    }

    senderImpl.setUsername(userName); // ,username
    senderImpl.setPassword(password); // , password
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true"); // true,
    prop.put("mail.smtp.timeout", "25000");
    senderImpl.setJavaMailProperties(prop);
    // 
    senderImpl.send(mailMessage);
}

From source file:com.rxx.common.util.MailUtil.java

/**
 * html/*from w w  w .j  a v a2 s  . co m*/
 *
 * @param host 
 * @param port
 * @param userName
 * @param password
 * @param title
 * @param contenthtml
 * @param imgs
 * @param toUser
 * @throws javax.mail.MessagingException
 */
public static void sendNews(String host, int port, String userName, String password, String title,
        String content, List<String> imgs, String[] toUser)
        throws MessagingException, javax.mail.MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    // mail server
    senderImpl.setHost(host);

    // ,html
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // boolean,MimeMessageHelpertrue
    // multipart
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);

    // 
    messageHelper.setTo(toUser);
    messageHelper.setFrom(userName);
    messageHelper.setSubject(title);
    // true HTML
    messageHelper.setText(content, true);

    int i = 0;
    for (String imagePath : imgs) {
        FileSystemResource img = new FileSystemResource(new File(imagePath));
        messageHelper.addInline(i + "", img);
        i++;
    }

    senderImpl.setUsername(userName); // ,username
    senderImpl.setPassword(password); // , password
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true"); // true,
    prop.put("mail.smtp.timeout", "25000");
    senderImpl.setJavaMailProperties(prop);
    // 
    senderImpl.send(mailMessage);

    // 
    senderImpl.send(mailMessage);
}

From source file:com.rxx.common.util.MailUtil.java

/**
 * html/*  ww w.j  a  v a  2s.c o m*/
 *
 * @param host 
 * @param port
 * @param userName
 * @param password
 * @param title
 * @param contenthtml
 * @param toUser
 * @throws javax.mail.MessagingException
 */
public static void sendHtml(String host, int port, String userName, String password, String title,
        String content, String[] toUser) {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    // mail server
    senderImpl.setHost(host);
    senderImpl.setPort(port);
    // ,html
    MimeMessage mailMessage = senderImpl.createMimeMessage();

    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");

        try {
            // 
            messageHelper.setTo(toUser);
            messageHelper.setFrom(userName);
            messageHelper.setSubject(title);
            // true HTML
            messageHelper.setText(content, true);
        } catch (javax.mail.MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        senderImpl.setUsername(userName); // ,username
        senderImpl.setPassword(password); // , password
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true"); // true,
        prop.put("mail.smtp.timeout", "25000");
        senderImpl.setJavaMailProperties(prop);
        // 
        senderImpl.send(mailMessage);
    } catch (javax.mail.MessagingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

From source file:hu.petabyte.redflags.web.svc.EmailSvc.java

public boolean send(String to, String subject, String text) {
    try {//from  w w w  . j av a 2 s. c  o  m
        JavaMailSenderImpl sender = (JavaMailSenderImpl) mailSender;
        MimeMessage mail = sender.createMimeMessage();
        mail.setContent(text.replaceAll("\n", "<br\\>\n").trim(), "text/html; charset=UTF-8");
        MimeMessageHelper helper = new MimeMessageHelper(mail, false, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        sender.send(mail);
        LOG.trace("E-mail sent with subject: {}", subject);
        return true;
    } catch (Exception ex) {
        LOG.warn("Failed to send email (subject: " + subject + ").", ex);
        return false;
    }
}

From source file:io.gravitee.management.rest.spring.EmailConfiguration.java

@Bean
public MimeMessageHelper mailMessage(JavaMailSenderImpl mailSender) throws MessagingException {
    final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
    mimeMessageHelper.setFrom(from);/* www. j  av a2s .co m*/
    return mimeMessageHelper;
}

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  w w  . j  a  va 2  s .c o  m*/
    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:com.cerebro.provevaadin.smtp.ConfigurazioneSMTPSpring.java

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);/* w  w w  . j  a v a 2 s  . c  om*/
    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: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);/*from   ww w.  ja v a2s  . com*/
    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:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {// www . j a  v a  2  s .c om
        // 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();
    }
}