org.springframework.mail.javamail.MimeMessagePreparator Java Examples

The following examples show how to use org.springframework.mail.javamail.MimeMessagePreparator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: pacbot   Author: tmobile   File: MailService.java    License: Apache License 2.0 6 votes vote down vote up
private MimeMessagePreparator buildMimeMessagePreparator(String from, List<String> to, String subject, String mailContent , final String attachmentUrl) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		messageHelper.setText(mailContent, true);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
	};
	return messagePreparator;
}
 
Example #2
Source Project: auth-server   Author: gigsterous   File: EmailService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Prepare Mime message and send it using java mail sender.
 * </p>
 */
@Async
public void prepareAndSend(String to, String from, String subject, String message, String link) {
  MimeMessagePreparator messagePreparator = mimeMessage -> {
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
    messageHelper.setFrom(from);
    messageHelper.setTo(to);
    messageHelper.setSubject(subject);

    String content = mailContentBuilder.build(message, link);
    messageHelper.setText(content, true);
  };

  log.debug("Sending email...");
  mailSender.send(messagePreparator);
}
 
Example #3
Source Project: cms   Author: myxzjie   File: RegisterSystemListener.java    License: Apache License 2.0 6 votes vote down vote up
@Async
    @Order
    @EventListener(EmailEvent.class)
    public void emailListener(EmailEvent event) {
        MimeMessagePreparator mailMessage = mimeMessage -> {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setFrom(from, fromName);
            for (String to : event.getTos()) {
                message.addTo(to);
            }
            message.setSubject(event.getSubject());
            message.setText(event.getContent(), true);
//            String html = "<html><body><h4>Hello,SpringBoot</h4><img src='cid:boot' /></body></html>";
//            mimeMessageHelper.setText(html, true);
            // 设置内嵌元素 cid,第一个参数表示内联图片的标识符,第二个参数标识资源引用
//            mimeMessageHelper.addInline("boot", new ClassPathResource("public/images/boot.png"));
            //添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
        };

        mailSender.send(mailMessage);
    }
 
Example #4
Source Project: olat   Author: huihoo   File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

            message.setTo(mailParameters.getToMailAddress());
            message.setFrom(mailParameters.getFromMailAddress());
            message.setSubject(mailParameters.getSubject());
            if (mailParameters.hasCcMailAddress()) {
                message.setCc(mailParameters.getCcMailAddress());
            }
            if (mailParameters.hasReplyTo()) {
                message.setReplyTo(mailParameters.getReplyTo());
            }
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
            log.debug("*** TEST text='" + text + "'");
            message.setText(text, true);
            message.setValidateAddresses(true);

        }
    };
    this.mailSender.send(preparator);
}
 
Example #5
Source Project: olat   Author: huihoo   File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

            message.setTo(mailParameters.getToMailAddress());
            message.setFrom(mailParameters.getFromMailAddress());
            message.setSubject(mailParameters.getSubject());
            if (mailParameters.hasCcMailAddress()) {
                message.setCc(mailParameters.getCcMailAddress());
            }
            if (mailParameters.hasReplyTo()) {
                message.setReplyTo(mailParameters.getReplyTo());
            }
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
            log.debug("*** TEST text='" + text + "'");
            message.setText(text, true);
            message.setValidateAddresses(true);

        }
    };
    this.mailSender.send(preparator);
}
 
Example #6
Source Project: olat   Author: huihoo   File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendMailWithAttachments(final TemplateWithAttachmentMailTO template) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.addTo(template.getToMailAddress());
            message.setFrom(template.getFromMailAddress());
            message.setSubject(template.getSubject());
            if (template.hasCcMailAddress()) {
                message.setCc(template.getCcMailAddress());
            }
            if (template.hasReplyTo()) {
                message.setReplyTo(template.getReplyTo());
            }

            // add attachments if any
            List<File> attachments = template.getAttachments();
            for (File file : attachments) {
                message.addAttachment(file.getName(), file);
            }

            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template.getTemplateLocation(), template.getTemplateProperties());
            message.setText(text, true);
            message.setValidateAddresses(true);
        }
    };
    this.mailSender.send(preparator);
}
 
Example #7
Source Project: JDeSurvey   Author: JD-Software   File: MailService.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param toEmailAddress
 * @param ccEmailAdress
 * @param emailSubject
 * @param emailHtmlBodyText
 */
public void sendEmail(final String toEmailAddress,
					  final String ccEmailAdress,
   					  final String emailSubject,
   					  final String emailHtmlBodyText) {
   	
   	MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
   			MimeMessageHelper message = new MimeMessageHelper(mimeMessage);    			
   			message.setTo(toEmailAddress);
   			message.setCc(ccEmailAdress);
   			message.setSubject(emailSubject);
   			message.setText(emailHtmlBodyText, true);
   		}
   	};
   	mailSender.send(preparator);
   }
 
Example #8
Source Project: JDeSurvey   Author: JD-Software   File: MailService.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * List of cc required
 */
public void sendEmail(final String toEmailAddress,
					  final String[] ccEmailAdress,
   					  final String emailSubject,
   					  final String emailHtmlBodyText) {
   	
   	MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
   			MimeMessageHelper message = new MimeMessageHelper(mimeMessage);    			
   			message.setTo(toEmailAddress);
   			message.setCc(ccEmailAdress);
   			message.setSubject(emailSubject);
   			message.setText(emailHtmlBodyText, true);
   		}
   	};
   	mailSender.send(preparator);
   }
 
Example #9
Source Project: voj   Author: hzxie   File: MailSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送电子邮件到指定收件人.
 * @param recipient - 收件人的电子邮件地址
 * @param subject - 邮件的主题
 * @param body - 邮件的内容
 */
public void sendMail(final String recipient, final String subject, final String body) { 
	final MimeMessagePreparator preparator = new MimeMessagePreparator() {
		public void prepare(MimeMessage mimeMessage) 
				throws MessagingException, UnsupportedEncodingException {
			MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
			message.setTo(recipient);
			message.setFrom(senderMail, senderName);
			message.setSubject(subject);
			message.setText(body, true);
		}
	};
	new Thread(new Runnable() {
		public void run() {
			mailSender.send(preparator);
			LOGGER.info(String.format("An Email{Recipient: %s, Subject: %s} has been sent.", 
					new Object[] {recipient, subject}));
		}
	}).start();
}
 
Example #10
Source Project: podcastpedia-web   Author: PodcastpediaOrg   File: EmailNotificationServiceImpl.java    License: MIT License 6 votes vote down vote up
public void sendContactNotification(final ContactForm contactForm) {
      MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
		public void prepare(MimeMessage mimeMessage) throws Exception {
             MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
             message.setTo(configService.getValue("EMAIL_TO_CONTACT_MESSAGE"));
             message.setBcc("[email protected]");
             message.setFrom(new InternetAddress(contactForm.getEmail()));
             message.setSubject("New contact message " + contactForm.getTopic());
             message.setReplyTo(contactForm.getEmail());
             message.setSentDate(new Date());
             Map model = new HashMap();	             
             model.put("newMessage", contactForm);
             
             String text = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, "velocity/newContactMessageToAdmin.vm", "UTF-8", model);
             message.setText(text, true);
          }
       };
       this.mailSender.send(preparator);	  
}
 
Example #11
Source Project: podcastpedia-web   Author: PodcastpediaOrg   File: EmailNotificationServiceImpl.java    License: MIT License 6 votes vote down vote up
public void sendSuggestPodcastNotification(final SuggestedPodcast suggestedPodcast) {
      MimeMessagePreparator preparator = new MimeMessagePreparator() {
	        @SuppressWarnings({ "rawtypes", "unchecked" })
			public void prepare(MimeMessage mimeMessage) throws Exception {
	             MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	             message.setTo(configService.getValue("EMAIL_TO_SUGGEST_PODCAST"));
	             message.setBcc("[email protected]");
	             message.setFrom(new InternetAddress(suggestedPodcast.getEmail()) );
	             message.setSubject("New suggested podcast");
	             message.setSentDate(new Date());
	             Map model = new HashMap();	             
	             model.put("newPodcast", suggestedPodcast);		             
	             String text = VelocityEngineUtils.mergeTemplateIntoString(
	                velocityEngine, "velocity/suggestPodcastNotificationMessage.vm", "UTF-8", model);
	             message.setText(text, true);
	          }
	       };
	       mailSender.send(preparator);			
}
 
Example #12
Source Project: dubai   Author: guuuuo   File: SendRegisterNotificationTask.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    javaMailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            Validate.notEmpty(user.getEmail());
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setTo(user.getEmail());
            messageHelper.setSentDate(new Date());
            messageHelper.setSubject("Please active your account");
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("properties", properties);
            root.put("user", user);
            messageHelper.setText(TemplateContentProcessor.processTemplateWithFile("register-notification.ftl", root), true);
        }
    });

}
 
Example #13
Source Project: dubai   Author: guuuuo   File: SendResetPasswordNotificationTask.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    javaMailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            Validate.notEmpty(user.getEmail());
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setTo(user.getEmail());
            messageHelper.setSentDate(new Date());
            messageHelper.setSubject("Please reset your password");
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("properties", properties);
            root.put("user", user);
            messageHelper.setText(TemplateContentProcessor.processTemplateWithFile("reset-password-notification.ftl", root), true);
        }
    });

}
 
Example #14
Source Project: Lottery   Author: caipiao   File: UnifiedUserMngImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void senderEmail(final Integer uid, final String username,
		final String to, final String resetKey, final String resetPwd,
		final EmailSender email, final MessageTemplate tpl) {
	JavaMailSenderImpl sender = new JavaMailSenderImpl();
	sender.setHost(email.getHost());
	sender.setUsername(email.getUsername());
	sender.setPassword(email.getPassword());
	sender.send(new MimeMessagePreparator() {
		public void prepare(MimeMessage mimeMessage)
				throws MessagingException, UnsupportedEncodingException {
			MimeMessageHelper msg = new MimeMessageHelper(mimeMessage,
					false, email.getEncoding());
			msg.setSubject(tpl.getForgotPasswordSubject());
			msg.setTo(to);
			msg.setFrom(email.getUsername(), email.getPersonal());
			String text = tpl.getForgotPasswordText();
			text = StringUtils.replace(text, "${uid}", String.valueOf(uid));
			text = StringUtils.replace(text, "${username}", username);
			text = StringUtils.replace(text, "${resetKey}", resetKey);
			text = StringUtils.replace(text, "${resetPwd}", resetPwd);
			msg.setText(text);
		}
	});
}
 
Example #15
Source Project: ods-provisioning-app   Author: opendevstack   File: MailAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public void notifyUsersAboutProject(OpenProjectData data) {
  if (!isMailEnabled) {
    logger.debug("Do not send email, because property mail.enabled is set to false.");
    return;
  }
  String recipient = manager.getUserEmail();
  MimeMessagePreparator messagePreparator =
      mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom(mailSenderAddress);
        messageHelper.setTo(recipient);
        messageHelper.setSubject("ODS Project provision update");
        messageHelper.setText(build(data), true);
      };

  Thread sendThread =
      new Thread(
          () -> {
            try {
              MDC.put(STR_LOGFILE_KEY, data.projectKey);
              mailSender.send(messagePreparator);
            } catch (MailException e) {
              logger.error("Error in sending mail for project: " + data.projectKey, e);
            } finally {
              MDC.remove(STR_LOGFILE_KEY);
            }
          });

  sendThread.start();
  logger.debug("Mail for project: {} sent", data.projectKey);
}
 
Example #16
Source Project: pacbot   Author: tmobile   File: MailService.java    License: Apache License 2.0 5 votes vote down vote up
private MimeMessagePreparator buildMimeMessagePreparator(String cc,String from, List<String> to, String subject, String mailMessageUrlOrBody, Map<String, Object> placeholderValues, final String attachmentUrl, final Boolean isPlainMessage) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		
		if(!StringUtils.isEmpty(cc)){
		messageHelper.setCc(cc);
		}
		
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
		String content = StringUtils.EMPTY;
		if(isPlainMessage) {
			content = mailContentBuilderService.buildPlainTextMail(mailMessageUrlOrBody, placeholderValues);
		} else {
			if(!isHttpUrl(mailMessageUrlOrBody)) {
				File template = new ClassPathResource("templates/".concat(mailMessageUrlOrBody).concat(".html")).getFile();
				content = mailContentBuilderService.buildPlainTextMail(FileUtils.readFileToString(template, "UTF-8"), placeholderValues);
			} else {
				String mailBody = mailContentBuilderService.getRemoteMailContent(mailMessageUrlOrBody);
				content = mailContentBuilderService.buildPlainTextMail(mailBody, placeholderValues);
			}
		}
		messageHelper.setText(content, true);
	};
	return messagePreparator;
}
 
Example #17
Source Project: pacbot   Author: tmobile   File: MailService.java    License: Apache License 2.0 5 votes vote down vote up
private MimeMessagePreparator prepareTemplateBuildMimeMessagePreparator(String from, List<String> to, String subject, String mailMessageUrlOrBody, Map<String, Object> templateModelValues, final String attachmentUrl, final Boolean isPlainMessage) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
		String content = StringUtils.EMPTY;
		if(isPlainMessage) {
			content = mailContentBuilderService.buildPlainTextMail(mailMessageUrlOrBody, templateModelValues);
		} else {
			if(!isHttpUrl(mailMessageUrlOrBody)) {
				File template = new ClassPathResource("templates/".concat(mailMessageUrlOrBody).concat(".html")).getFile();
				content = mailContentBuilderService.buildPlainTextMail(FileUtils.readFileToString(template, "UTF-8"), templateModelValues);
			} else {
				content = processTemplate(mailMessageUrlOrBody, templateModelValues);
			}
		}
		messageHelper.setText(content, true);
	};
	return messagePreparator;
}
 
Example #18
Source Project: cloud-portal   Author: chrisipa   File: MailService.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void send(String to, String subject, String templatePath, List<File> attachmentList, Map variableMap) {

	// logging
	LOG.info("Sending mail from '{}' to address '{}' and cc addresses '{}' with subject '{}'", from, to, cc, subject);

	// really send mail
	if (send) {

		// create mime message preparator
		MimeMessagePreparator preparator = new MimeMessagePreparator() {

			@SuppressWarnings("unchecked")
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {

				// get mail text by substituting variables in mail template with velocity
				String text = velocityService.evaluate(templatePath, variableMap);

				// create message helper
				MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
				messageHelper.setFrom(from);
				messageHelper.setTo(to);
				messageHelper.setCc(cc.split(","));
				messageHelper.setSubject(subject);
				messageHelper.setText(text, true);
				
				// add attachments if available
				for (File file : attachmentList) {
					messageHelper.addAttachment(file.getName(), file);
				}
			}
		};

		// send HTML mail
		mailSender.send(preparator);
	}
}
 
Example #19
Source Project: scoold   Author: Erudika   File: ScooldEmailer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean sendEmail(final List<String> emails, final String subject, final String body) {
	if (emails == null || emails.isEmpty()) {
		return false;
	}
	asyncExecute(new Runnable() {
		public void run() {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper msg = new MimeMessageHelper(mimeMessage);
					if (emails.size() == 1) {
						msg.setTo(emails.iterator().next());
					} else {
						msg.setBcc(emails.toArray(new String[0]));
					}
					msg.setSubject(subject);
					msg.setFrom(Config.SUPPORT_EMAIL, Config.APP_NAME);
					msg.setText(body, true); // body is assumed to be HTML
				}
			};
			try {
				mailSender.send(preparator);
				logger.debug("Email sent to {}, {}", emails, subject);
			} catch (MailException ex) {
				logger.error("Failed to send email to [{}] with body [{}]. {}", emails, body, ex.getMessage());
			}
		}
	});
	return true;
}
 
Example #20
Source Project: cerebro   Author: voyages-sncf-technologies   File: MailSenderImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void send(final String title, final String text, final List<String> recipients) {
    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setTo(toInternetAddresses(recipients));
        message.setFrom(properties.getProperty("sender"));
        message.setSubject(title);
        message.setSentDate(new Date());

        message.setText(text, true);
    };
    LOGGER.debug("send mail with title: {}", title);
    mailSender.send(preparator);
}
 
Example #21
Source Project: waltz   Author: finos   File: WaltzEmailer.java    License: Apache License 2.0 5 votes vote down vote up
public void sendEmail(String subject,
                      String body,
                      String[] to) {

    if (this.mailSender == null) {
        LOG.warn("Not sending email.  No mailer provided.");
        return;
    }
    Checks.checkNotEmpty(subject, "subject cannot be empty");
    Checks.checkNotEmpty(body, "body cannot be empty");
    Checks.checkNotEmpty(to, "to cannot be empty");
    Checks.checkAll(to, StringUtilities::notEmpty, "email address cannot be empty");

    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
        message.setSubject(subject);
        message.setFrom(fromEmail);
        message.setBcc(to);
        message.addAttachment("waltz.png", IOUtilities.getFileResource("/images/waltz.png"));
        message.addAttachment("client-logo", IOUtilities.getFileResource("/templates/images/client-logo.png"));

        Map model = new HashMap();
        model.put("body", body);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

        try(InputStreamReader templateReader = new InputStreamReader(IOUtilities
                .getFileResource(DEFAULT_EMAIL_TEMPLATE_LOCATION)
                .getInputStream())) {
            Template template = new Template("template", templateReader, cfg);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            message.setText(text, true);
        }
    };

    this.mailSender.send(preparator);
}
 
Example #22
Source Project: olat   Author: huihoo   File: JavaMailSenderDummyImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(MimeMessagePreparator msg) throws MailException {
    try {
        msg.prepare(mimeMessageDummy);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    logMail(msg);
}
 
Example #23
Source Project: olat   Author: huihoo   File: JavaMailSenderDummyImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void logMail(MimeMessagePreparator mimeMessagePreparator) {
    try {
        MimeMessage message = new MimeMessage((Session) null);
        mimeMessagePreparator.prepare(message);
        logMail(message);
    } catch (Exception e) {
        log.error("Mail Test-Mode: couldn't send mail with MimeMessagePreparator=" + mimeMessagePreparator.toString());
    }
}
 
Example #24
Source Project: JDeSurvey   Author: JD-Software   File: MailService.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * No cc required
 */
public void sendEmail(final String toEmailAddress,			 
					  final String emailSubject,
					  final String emailHtmlBodyText) {

		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
			MimeMessageHelper message = new MimeMessageHelper(mimeMessage);			
			message.setTo(toEmailAddress);				
			message.setSubject(emailSubject);
			message.setText(emailHtmlBodyText, true);
		  }
		};
		mailSender.send(preparator);
}
 
Example #25
Source Project: para   Author: Erudika   File: JavaMailEmailer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean sendEmail(final List<String> emails, final String subject, final String body) {
	if (emails == null || emails.isEmpty()) {
		return false;
	}
	asyncExecute(new Runnable() {
		public void run() {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper msg = new MimeMessageHelper(mimeMessage);
					Iterator<String> emailz = emails.iterator();
					msg.setTo(emailz.next());
					while (emailz.hasNext()) {
						msg.addBcc(emailz.next());
					}
					msg.setSubject(subject);
					msg.setFrom(Config.SUPPORT_EMAIL);
					msg.setText(body, true); // body is assumed to be HTML
				}
			};
			try {
				mailSender.send(preparator);
				logger.debug("Email sent to {}, {}", emails, subject);
			} catch (MailException ex) {
				logger.error("Failed to send email. {}", ex.getMessage());
			}
		}
	});
	return true;
}
 
Example #26
Source Project: spring-cloud-aws   Author: spring-cloud   File: SimpleEmailServiceJavaMailSender.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(MimeMessagePreparator... mimeMessagePreparators)
		throws MailException {
	MimeMessage mimeMessage = createMimeMessage();
	for (MimeMessagePreparator mimeMessagePreparator : mimeMessagePreparators) {
		try {
			mimeMessagePreparator.prepare(mimeMessage);
		}
		catch (Exception e) {
			throw new MailPreparationException(e);
		}
	}
	send(mimeMessage);
}
 
Example #27
Source Project: alf.io   Author: alfio-event   File: SmtpMailer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void send(EventAndOrganizationId event, String fromName, String to, List<String> cc, String subject, String text,
                 Optional<String> html, Attachment... attachments) {

    var conf = configurationManager.getFor(Set.of(SMTP_FROM_EMAIL, MAIL_REPLY_TO,
        SMTP_HOST, SMTP_PORT, SMTP_PROTOCOL,
        SMTP_USERNAME, SMTP_PASSWORD, SMTP_PROPERTIES), ConfigurationLevel.event(event));

    MimeMessagePreparator preparator = mimeMessage -> {

        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments) ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
                : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(conf.get(SMTP_FROM_EMAIL).getRequiredValue(), fromName);
        String replyTo = conf.get(MAIL_REPLY_TO).getValueOrDefault("");
        if(StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if(cc != null && !cc.isEmpty()){
            message.setCc(cc.toArray(new String[0]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }

        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()), a.getContentType());
            }
        }
        
        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(conf).send(preparator);
}
 
Example #28
Source Project: cloudbreak   Author: hortonworks   File: EmailMimeMessagePreparator.java    License: Apache License 2.0 5 votes vote down vote up
public MimeMessagePreparator prepareMessage(String to, String subject, String body) {
    return mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(msgFrom);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body, true);
    };
}
 
Example #29
Source Project: studio   Author: craftercms   File: EmailMessageSender.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected boolean sendEmail(final String subject, final String content, final String userEmailAddress,
                            final String replyTo, final String personalFromName) {
    boolean success = true;
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(userEmailAddress));
            InternetAddress[] replyTos = new InternetAddress[1];
            if ((replyTo != null) && (!"".equals(replyTo))) {
                replyTos[0] = new InternetAddress(replyTo);
                mimeMessage.setReplyTo(replyTos);
            }
            InternetAddress fromAddress = new InternetAddress(getDefaultFromAddress());
            if (personalFromName != null)
                fromAddress.setPersonal(personalFromName);
            mimeMessage.setFrom(fromAddress);
            mimeMessage.setContent(content, "text/html; charset=utf-8");
            mimeMessage.setSubject(subject);
            logger.debug("sending email to [" + userEmailAddress + "]subject subject :[" + subject + "]");
        }
    };
    try {
        if (isAuthenticatedSMTP()) {
            emailService.send(preparator);
        } else {
            emailServiceNoAuth.send(preparator);
        }
    } catch (MailException ex) {
        // simply log it and go on...
        logger.error("Error sending email notification to:" + userEmailAddress, ex);

        success = false;
    }

    return success;
}
 
Example #30
Source Project: auth-server   Author: gigsterous   File: EmailServiceTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGivenEmailServiceWhenSendingEmailThenVerifyEmailSentThroughMailSender() throws MessagingException {
  emailService.prepareAndSend("[email protected]", "[email protected]", "test", "Hello!", "http://www.example.com");

  verify(mailSender).send(any(MimeMessagePreparator.class));
}