List of usage examples for org.springframework.mail.javamail MimeMessageHelper setTo
public void setTo(String[] to) throws MessagingException
From source file:net.triptech.metahive.service.EmailSenderService.java
/** * Send an email message using the configured Spring sender. On success * record the sent message in the datastore for reporting purposes * * @param email the email//from w w w .ja v a 2 s . c o m * @param attachments the attachments * @throws ServiceException the service exception */ public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments) throws ServiceException { // Check to see whether the required fields are set (to, from, message) if (email.getTo() == null) { throw new ServiceException("Error sending email: Recipient " + "address required"); } if (StringUtils.isBlank(email.getFrom())) { throw new ServiceException("Error sending email: Email requires " + "a from address"); } if (StringUtils.isBlank(email.getText())) { throw new ServiceException("Error sending email: No email " + "message specified"); } if (mailSender == null) { throw new ServiceException("The JavaMail sender has not " + "been configured"); } // Prepare the email message MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = null; boolean htmlMessage = false; if (StringUtils.containsIgnoreCase(email.getText(), "<html")) { htmlMessage = true; try { helper = new MimeMessageHelper(message, true, "UTF-8"); } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } } else { helper = new MimeMessageHelper(message); } try { helper.setTo(email.getTo()); helper.setFrom(email.getFrom()); helper.setSubject(email.getSubject()); if (email.getCc() != null) { helper.setCc(email.getCc()); } if (email.getBcc() != null) { helper.setBcc(email.getBcc()); } if (htmlMessage) { String plainText = email.getText(); try { ConvertHtmlToText htmlToText = new ConvertHtmlToText(); plainText = htmlToText.convert(email.getText()); } catch (Exception e) { logger.error("Error converting HTML to plain text: " + e.getMessage()); } helper.setText(plainText, email.getText()); } else { helper.setText(email.getText()); } if (email.getSentDate() != null) { helper.setSentDate(email.getSentDate()); } else { helper.setSentDate(Calendar.getInstance().getTime()); } } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } // Append any attachments (if an HTML email) if (htmlMessage && attachments != null) { for (String id : attachments.keySet()) { Object reference = attachments.get(id); if (reference instanceof File) { try { FileSystemResource res = new FileSystemResource((File) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending File attachment: " + me.getMessage()); } } if (reference instanceof URL) { try { UrlResource res = new UrlResource((URL) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending URL attachment: " + me.getMessage()); } } } } // Send the email message try { mailSender.send(message); } catch (MailException me) { logger.error("Error sending email: " + me.getMessage()); throw new ServiceException("Error sending email: " + me.getMessage()); } }
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.j a v a 2s .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:de.thm.arsnova.service.UserServiceImpl.java
private void sendEmail(UserProfile userProfile, String subject, String body) { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8"); try {/*from w ww. j av a 2s . c o m*/ helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">"); helper.setTo(userProfile.getLoginId()); helper.setSubject(subject); helper.setText(body); logger.info("Sending mail \"{}\" from \"{}\" to \"{}\"", subject, msg.getFrom(), userProfile.getLoginId()); mailSender.send(msg); } catch (MailException | MessagingException e) { logger.warn("Mail \"{}\" could not be sent.", subject, e); } }
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
@RequestMapping(value = "/app", params = { "delete" }) public ModelAndView deleteApp(@RequestParam("delete") Long id, Authentication authentication) { UserDetails user = (UserDetails) authentication.getPrincipal(); Developer developer = appManagement.getDeveloper(user.getUsername()); log.debug("User {} deleted the app with id {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), id); if (developer == null) { return new ModelAndView("redirect:register_developer"); } else {//w ww . j a v a 2s . c om Application application = appManagement.getApplication(id); log.debug("Deleting the app {}.", application.getName()); if (application.getDeveloper().getResidentIdentificationNumber().equals(user.getUsername())) { appManagement.removeApplication(id); try { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(mailAddress); helper.setFrom(new InternetAddress(mailFrom)); helper.setSubject("Borttagen app: " + application.getName()); helper.setText("Utvecklare med personnr " + user.getUsername() + " har tagit bort appen: " + application.getName()); sender.send(message); } catch (Exception e) { log.error("Caught exception while trying to send email", e); } } else { throw new RuntimeException( "The logged in user is not the same as the developer of the application!"); } return new ModelAndView("redirect:"); } }
From source file:org.wallride.service.UserService.java
@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true) public UserInvitation inviteAgain(UserInvitationResendRequest form, BindingResult result, AuthorizedUser authorizedUser) throws MessagingException { LocalDateTime now = LocalDateTime.now(); UserInvitation invitation = userInvitationRepository.findOneForUpdateByToken(form.getToken()); invitation.setExpiredAt(now.plusHours(72)); invitation.setUpdatedAt(now);//from w w w . j a v a 2 s .co m invitation.setUpdatedBy(authorizedUser.toString()); invitation = userInvitationRepository.saveAndFlush(invitation); Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath().path("/_admin/signup") .queryParam("token", invitation.getToken()).buildAndExpand().toString(); final Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("websiteTitle", websiteTitle); ctx.setVariable("authorizedUser", authorizedUser); ctx.setVariable("signupLink", signupLink); ctx.setVariable("invitation", invitation); final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject(MessageFormat.format( messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()), authorizedUser.toString(), websiteTitle)); message.setFrom(authorizedUser.getEmail()); message.setTo(invitation.getEmail()); final String htmlContent = templateEngine.process("user-invite", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); return invitation; }
From source file:org.gaixie.micrite.mail.impl.EmailSenderImpl.java
public void sendEmail(String from, List<String> recipients, String subj, String text) { final String fm = from; final String s = subj; final String tpl = text; for (final String to : recipients) { // ?????? Runnable thread = new Runnable() { public void run() { try { mailSender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8"); if (fm != null) helper.setFrom(fm); else helper.setFrom("micrite-noreply@gmail.com"); if (s != null) helper.setSubject(s); else helper.setSubject("no subject"); if (tpl != null) helper.setText(tpl); else helper.setText("no text"); helper.setTo(to); }//from w w w. jav a2 s . c o m }); } catch (MailException ex) { // simply log it and go on... System.err.println(ex.getMessage()); } } }; new Thread(thread).start(); } }
From source file:it.jugpadova.blo.EventBo.java
private void sendConfirmationEmail(final Event event, final Participant participant, final String baseUrl) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @SuppressWarnings(value = "unchecked") public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(participant.getEmail()); message.setFrom(conf.getConfirmationSenderEmailAddress()); message.setSubject("Please confirm event registration"); Map model = new HashMap(); model.put("participant", participant); model.put("event", event); model.put("baseUrl", baseUrl); model.put("confirmationCode", URLEncoder.encode(participant.getConfirmationCode(), "UTF-8")); model.put("email", URLEncoder.encode(participant.getEmail(), "UTF-8")); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "it/jugpadova/registration-confirmation.vm", model); message.setText(text, true); }/*from w w w . j av a2 s . c om*/ }; this.mailSender.send(preparator); }
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
@RequestMapping(value = "/app", method = RequestMethod.POST) public String registerApp(ModelMap model, @ModelAttribute("application") Application application, @RequestParam("certificate") MultipartFile certificate, MultipartFile icon, BindingResult result, Authentication authentication) throws IOException { UserDetails user = (UserDetails) authentication.getPrincipal(); Developer developer = appManagement.getDeveloper(user.getUsername()); log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());/*from w w w . j a v a 2 s .co m*/ if (developer == null) { return "redirect:register_developer"; } else { applicationValidator.validate(application, result); application.setRegistrationDate(new Date()); application.setState(State.REGISTRATED); application.setDeveloper(developer); Application existingApp = appManagement.getApplicationByClientId(application.getClientId()); if (existingApp != null) { result.rejectValue("clientId", "invalid.clientId", "Klient id:et finns redan registrerat, var god vlj ett annat."); } // validate icon if it exists if (application.getIcon() != null && application.getIcon().length > 0) { try { ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon()); BufferedImage bufferedImage = ImageIO.read(bis); log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight()); application.setIconContentType(icon.getContentType()); // TODO: Check width and height here! } catch (Exception e) { result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig"); } } //For now we are just allowing the addition of just one certificate List<Certificate> certs = new ArrayList<>(); if (certificate != null && certificate.getSize() > 0) { certs.add(createCertificate(certificate, result)); } if (result.hasErrors()) { List<Permission> permissions = permissionServices.getAllPermissions(); model.addAttribute("scopes", permissions); return "register_application"; } Application savedApp = appManagement.registerApplication(application); for (Certificate cert : certs) { cert.setApplication(savedApp); appManagement.saveCertificate(cert); savedApp.getCertificates().add(cert); } try { log.debug("Composing message to: {}", mailAddress); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(mailAddress); helper.setFrom(new InternetAddress(mailFrom)); log.debug("Creating message for existing app. User {} edited the app {}", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName()); helper.setSubject("Redigerad app: " + application.getName()); helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: " + application.getName()); log.debug("Sending mail notification."); sender.send(message); } catch (Exception e) { log.error("Caught exception while trying to send email", e); } return "redirect:"; } }
From source file:org.wallride.service.UserService.java
@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true) public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) { User user = userRepository.findOneForUpdateById(request.getUserId()); if (user == null) { throw new IllegalArgumentException("The user does not exist"); }//from w ww. j av a2s . c o m PasswordEncoder passwordEncoder = new StandardPasswordEncoder(); user.setLoginPassword(passwordEncoder.encode(request.getPassword())); user.setUpdatedAt(LocalDateTime.now()); user.setUpdatedBy(passwordResetToken.getUser().toString()); user = userRepository.saveAndFlush(user); passwordResetTokenRepository.delete(passwordResetToken); try { Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath(); if (blog.isMultiLanguage()) { builder.path("/{language}"); } builder.path("/login"); Map<String, Object> urlVariables = new LinkedHashMap<>(); urlVariables.put("language", request.getLanguage()); urlVariables.put("token", passwordResetToken.getToken()); String loginLink = builder.buildAndExpand(urlVariables).toString(); Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("passwordResetToken", passwordResetToken); ctx.setVariable("resetLink", loginLink); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject(MessageFormat.format( messageSourceAccessor.getMessage("PasswordChangedSubject", LocaleContextHolder.getLocale()), blogTitle)); message.setFrom(mailProperties.getProperties().get("mail.from")); message.setTo(passwordResetToken.getEmail()); String htmlContent = templateEngine.process("password-changed", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); } catch (MessagingException e) { throw new ServiceException(e); } return user; }