List of usage examples for org.springframework.mail.javamail MimeMessageHelper setFrom
public void setFrom(String from) throws MessagingException
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
@RequestMapping(value = "/edit", method = RequestMethod.POST) public ModelAndView editApp(ModelMap model, Authentication authentication, @ModelAttribute("application") Application application, MultipartFile icon, @RequestParam(value = "certificate", required = false) MultipartFile certificate, BindingResult result) {//from www . j a v a 2s . co m UserDetails user = (UserDetails) authentication.getPrincipal(); Developer developer = appManagement.getDeveloper(user.getUsername()); List<Permission> permissions = permissionServices.getAllPermissions(); log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName()); if (developer == null) { return new ModelAndView("redirect:register_developer"); } else { applicationValidator.validate(application, result); log.info("app id: " + application.getId()); Application dbApp = appManagement.getApplication(application.getId()); if (!user.getUsername().equals(dbApp.getDeveloper().getResidentIdentificationNumber())) { throw new IllegalArgumentException( "The application developer is not the same as the logged in user"); } if (application.getIcon() == null && dbApp.getIcon() != null && dbApp.getIcon().length > 0) { application.setIcon(dbApp.getIcon()); log.debug("Icon wasn't updated this time around"); } else if (application.getIcon() != null) { log.debug("Icon was updated"); 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"); } } application.setCertificates(dbApp.getCertificates()); application.setRegistrationDate(dbApp.getRegistrationDate()); application.setState(dbApp.getState()); application.setDeveloper(developer); //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)); } //Error handling if (result.hasErrors()) { model.addAttribute(application); model.addAttribute("scopes", permissions); return new ModelAndView("application/edit"); } Application savedApp = appManagement.updateApplication(application); //Remove everything old. // Just allow one certificate to be set right now even though the model allows for more. //If this behavior is unwanted the GUI has to adapt for this as well as it only caters //for on certificate right now. if (certificate != null && certificate.getSize() > 0) { Set<Certificate> oldCerts = new HashSet<>(); //Clone in order to not get a concurrent modification exception for (Certificate cert : savedApp.getCertificates()) { oldCerts.add(cert); } //Remove anything old for (Certificate cert : oldCerts) { cert.setApplication(null); savedApp.getCertificates().remove(cert); appManagement.removeCertificate(cert); } //Set the new Certificate 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 new ModelAndView("redirect:/developer"); }
From source file:org.jasig.portlet.blackboardvcportlet.service.impl.MailTemplateServiceImpl.java
public void sendMail(final MailTask mt) { try {/*from w w w . j a va 2 s .c o m*/ MimeMessagePreparator messagePreparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true); if (mt.getMeetingInvite() != null) { CalendarOutputter outputter = new CalendarOutputter(); ByteArrayOutputStream os = new ByteArrayOutputStream(); outputter.setValidating(false); outputter.output(mt.getMeetingInvite(), os); message.addAttachment("invite.ics", new ByteArrayResource(os.toByteArray())); } message.setFrom(mt.getFrom() != null ? mt.getFrom() : defaultFromAddress); if (mt.getTo() != null) { String[] toArray = mt.getTo().toArray(new String[mt.getTo().size()]); message.setTo(toArray); } if (mt.getSubject() != null) { message.setSubject(mt.getSubject()); } else { switch (mt.getTemplate()) { case MODERATOR: message.setSubject(moderatorSubject); break; case INTERNAL_PARTICIPANT: message.setSubject(internalParticipantSubject); break; case EXTERNAL_PARTICIPANT: message.setSubject(externalParticipantSubject); break; case SESSION_DELETION: message.setSubject(sessionDeletionSubject); break; default: message.setSubject(""); } } message.setText(buildEmailMessage(mt), false); } }; mailSender.send(messagePreparator); } catch (Exception e) { logger.error("Issue with sending email", e); } }
From source file:com.seer.datacruncher.utils.mail.MailService.java
public void sendMail(MailConfig mailConfig) throws Exception { String logMsg = "MailService:sendMail():"; InputStream attachment = null; MimeMessage mimeMessage = null;//from w w w. j av a 2s.co m MimeMessageHelper helper = null; try { mimeMessage = mailSender.createMimeMessage(); helper = new MimeMessageHelper(mimeMessage, true); helper.setText(mailConfig.getText(), true); if (StringUtils.isEmpty(mailConfig.getMailTo())) { log.error("Invalid or empty 'toAddress' configured!!"); throw new Exception("Invalid or empty 'toAddress' configured"); } if (StringUtils.isEmpty(mailConfig.getMailFrom())) { log.error("Invalid or empty 'FromAddress' configured!!"); throw new Exception("Invalid or empty 'FromAddress' configured"); } if (!isEmailValid(mailConfig.getMailFrom())) { log.error("Invalid 'FromAddress' configured!!"); throw new Exception("Invalid 'FromAddress' configured"); } helper.setFrom(new InternetAddress(mailConfig.getMailFrom())); helper.setSubject(mailConfig.getSubject()); helper.setTo(getToAddress(mailConfig.getMailTo())); attachment = mailConfig.getAttachment(); if (attachment != null) { StreamAttachmentDataSource datasource = new StreamAttachmentDataSource(mailConfig.getAttachment()); helper.addAttachment(mailConfig.getAttachmentName(), datasource); } this.mailSender.send(mimeMessage); } catch (AuthenticationFailedException afex) { log.error(logMsg + "AuthenticationFailedException:", afex); throw new Exception("AuthenticationFailedException", afex); } catch (MessagingException mex) { log.error(logMsg + "Exception:", mex); throw new Exception("MessagingException", mex); } catch (Exception ex) { log.error(logMsg + "Exception:", ex); throw ex; } }
From source file:com.logicaalternativa.ejemplomock.rest.sender.SendMailCodePromotionImp.java
private void sendEmail(final PromotionCode promotionCode, final Locale locale) throws MessagingException { MimeMessage mimeMessage = getJavaMailSender().createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); final String subject = getMessageSource().getMessage("email.promotionCode.subject", new Object[] {}, "email.promotionCode.subject", locale); final String to = (new StringBuilder()) .append(promotionCode.getNameUser() != null ? promotionCode.getNameUser().toUpperCase() : "") .append("<").append(promotionCode.getEmail() != null ? promotionCode.getEmail() : "").append(">") .toString();//from w w w . j a v a 2s . c o m final String text = getMessageSource().getMessage("email.promotionCode.txt", new Object[] { promotionCode.getCode() }, "email.promotionCode.txt", locale); final String html = getMessageSource().getMessage("email.promotionCode.html", new Object[] { promotionCode.getCode() }, "email.promotionCode.html", locale); helper.setFrom(getFrom()); helper.setTo(to); helper.setSubject(subject); helper.setText(text, html); getJavaMailSender().send(mimeMessage); }
From source file:org.opentides.eventhandler.EmailHandler.java
public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body, File[] attachments) {/*from www . jav a 2 s. co m*/ try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(toInetAddress(to)); InternetAddress[] ccAddresses = toInetAddress(cc); if (ccAddresses != null) mimeMessageHelper.setCc(ccAddresses); InternetAddress[] bccAddresses = toInetAddress(bcc); if (bccAddresses != null) mimeMessageHelper.setBcc(bccAddresses); if (!StringUtil.isEmpty(replyTo)) mimeMessageHelper.setReplyTo(replyTo); Map<String, Object> templateVariables = new HashMap<String, Object>(); templateVariables.put("message-title", subject); templateVariables.put("message-body", body); StringWriter writer = new StringWriter(); VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer); mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName)); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(writer.toString(), true); // check for attachment if (attachments != null && attachments.length > 0) { for (File attachment : attachments) { mimeMessageHelper.addAttachment(attachment.getName(), attachment); } } /** * The name of the identifier should be image * the number after the image name is the counter * e.g. <img src="cid:image1" /> */ if (imagesPath != null && imagesPath.size() > 0) { int x = 1; for (String path : imagesPath) { FileSystemResource res = new FileSystemResource(new File(path)); String imageName = "image" + x; mimeMessageHelper.addInline(imageName, res); x++; } } javaMailSender.send(mimeMessage); } catch (MessagingException e) { _log.error(e, e); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } }
From source file:MailSender.java
public void send(Item item) { // major: well, sender is null, so no email is going out...silently. Just a debug message. // this means that the initial configuration is not able to create a sender. // This control should no be here and the methods that handle jndi or configFile should throw a // ConfigurationException if the sender is not created. if (sender == null) { logger.debug("mail sender is null, not sending notifications"); return;//from www . ja va 2 s . com } // TODO make this locale sensitive per recipient // major: don't use the comment to explain what the code is doing, just wrap the function in a // method with a talking name. This apply to all comments in this method. logger.debug("attempting to send mail for item update"); // prepare message content StringBuffer sb = new StringBuffer(); String anchor = getItemViewAnchor(item, defaultLocale); sb.append(anchor); // minor: why is not important here the user's locale like in the sendUserPassword method? sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale)); sb.append(anchor); if (logger.isDebugEnabled()) { logger.debug("html content: " + sb); } // prepare message MimeMessage message = sender.createMimeMessage(); // minor: I would use StandardCharsets.UTF_8.name() that return the canonical name // major: how do you test the use cases about the message? // the message is in the local stack so it can't be tested // better to implement a bridge pattern to decouple the messageHelper and pass it as // a collaborator. Although keep in mind that building the message is not a responsibility // of this class so this class should just send the message and not building it. MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); // Remember the TO person email to prevent duplicate mails // minor: recipient would be a better name for this variable // major: catching a general Exception is a bad idea. You are telling me // we could have a problem but when I'm reading it and I don't understand // what could go wrong (and, also, the try block is too long so that's one of // the reason I can't see what could go wrong) String toPersonEmail; try { helper.setText(addHeaderAndFooter(sb), true); helper.setSubject(getSubject(item)); helper.setSentDate(new Date()); helper.setFrom(from); // set TO if (item.getAssignedTo() != null) { helper.setTo(item.getAssignedTo().getEmail()); toPersonEmail = item.getAssignedTo().getEmail(); } else { helper.setTo(item.getLoggedBy().getEmail()); toPersonEmail = item.getLoggedBy().getEmail(); } // set CC List<String> cclist = new ArrayList<String>(); if (item.getItemUsers() != null) { for (ItemUser itemUser : item.getItemUsers()) { // Send only, if person is not the TO assignee if (!toPersonEmail.equals(itemUser.getUser().getEmail())) { cclist.add(itemUser.getUser().getEmail()); } } // sounds complicated but we have to ensure that no null // item will be set in setCC(). So we collect the cc items // in the cclist and transform it to an stringarray. if (cclist.size() > 0) { String[] cc = cclist.toArray(new String[0]); helper.setCc(cc); } } // send message // workaround: Some PSEUDO user has no email address. Because email // address // is mandatory, you can enter "no" in email address and the mail // will not // be sent. // major: this check is too late, we created everything and then we // won't use it. if (!"no".equals(toPersonEmail)) sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:jp.co.opentone.bsol.linkbinder.service.notice.impl.SendMailServiceImpl.java
public boolean sendMail(EmailNotice emailNotice) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); try {//from w w w . j a va 2 s.c o m helper.setSubject(emailNotice.getMhSubject()); helper.setText(emailNotice.getMailBody()); String[] addresses = convertEmpNoToMailAddress(emailNotice.getMhTo()); if (addresses.length == 0) { LOG.warn( "to???????????????????" + "??????email_notice.id = {}", emailNotice.getId()); return false; } helper.setBcc(addresses); // String [] from = convertEmpNoToMailAddress(emailNotice.getMhFrom()); // if (from.length == 0) { // LOG.warn("from???????????????????" // + "??????email_notice.id = {}", emailNotice.getId()); // return false; // } helper.setFrom(emailNotice.getMhFrom()); mailSender.send(message); return true; } catch (MessagingException e) { LOG.warn("??????", e); return false; } }
From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java
/** * {@inheritDoc}/* www .j a v a 2s.c o m*/ * @see com.mobileman.projecth.business.MailManager#sendTellAFriendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public void sendTellAFriendMessage(final String senderName, final String senderEmail, final String receiverEmails, final String body) { if (log.isDebugEnabled()) { log.debug("sendMessage(" + senderName + ", " + senderEmail + ", " + receiverEmails + ", " + body + ") - start"); } if (senderEmail == null || senderEmail.trim().length() == 0) { throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING); } if (receiverEmails == null || receiverEmails.trim().length() == 0) { throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING); } final String[] senderData = { "", "", "" }; final String[] receivers = receiverEmails.split("[,]"); for (int i = 0; i < receivers.length; i++) { final int idx = i; MimeMessagePreparator preparator = new MimeMessagePreparator() { /** * {@inheritDoc} * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage) */ @Override public void prepare(MimeMessage mimeMessage) throws Exception { if (log.isDebugEnabled()) { log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$ } MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING); messageHelper.setSentDate(new Date()); Map<String, Object> model = new HashMap<String, Object>(); model.put("body-text", body); String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "tell-a-friend-email-body.vm", model); String textMessage = HTMLTextParser.htmlToText(htmlMessage); messageHelper.setText(textMessage, htmlMessage); senderData[0] = htmlMessage; senderData[1] = textMessage; senderData[2] = "Mitteilung von projecth"; messageHelper.setSubject(senderData[2]); messageHelper.setTo(receivers[idx]); messageHelper.setFrom(getSystemAdminEmail()); if (log.isDebugEnabled()) { log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$ } } }; this.mailSender.send(preparator); } this.mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING); messageHelper.setSentDate(new Date()); messageHelper.setText(senderData[1], senderData[0]); messageHelper.setSubject(senderData[2]); messageHelper.setTo(senderEmail); messageHelper.setFrom(getSystemAdminEmail()); } }); if (log.isDebugEnabled()) { log.debug("sendMessage(...) - end"); } }
From source file:info.jtrac.mail.MailSender.java
public void sendUserPassword(User user, String clearText) { if (sender == null) { logger.debug("mail sender is null, not sending new user / password change notification"); return;/*from w w w . ja v a 2 s.c o m*/ } logger.debug("attempting to send mail for user password"); String localeString = user.getLocale(); Locale locale = null; if (localeString == null) { locale = defaultLocale; } else { locale = StringUtils.parseLocaleString(localeString); } MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); try { helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='jtrac'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:MailSender.java
public void sendUserPassword(User user, String clearText) { // major: well, sender is null, so no email is going out...silently. Just a debug message. // This means that the initial configuration is not able to create a sender. // This control should no be here and the methods that handle jndi or configFile should throw a // ConfigurationException if the sender is not created. if (sender == null) { logger.debug("mail sender is null, not sending new user / password change notification"); return;/*ww w. j av a 2 s . c o m*/ } logger.debug("attempting to send mail for user password"); String localeString = user.getLocale(); Locale locale = null; if (localeString == null) { locale = defaultLocale; } else { locale = StringUtils.parseLocaleString(localeString); } // major: there is a bit of code duplication with the method send. // Apparently it seems that just the body is changing but the rest is // really similar. As suggested above the way a message is created should be // refactored in a collaborator. This method should just send a message. MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); try { helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='jtrac'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); // major: generic exception, method too long, I don't understand what could fail. } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }