org.springframework.mail.javamail.MimeMessageHelper Java Examples

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper. 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 File: EmailServiceImpl.java    From tutorials with MIT License 8 votes vote down vote up
@Override
public void sendMessageWithAttachment(String to,
                                      String subject,
                                      String text,
                                      String pathToAttachment) {
    try {
        MimeMessage message = emailSender.createMimeMessage();
        // pass 'true' to the constructor to create a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(NOREPLY_ADDRESS);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
        helper.addAttachment("Invoice", file);

        emailSender.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: MailController.java    From spring-boot-study with MIT License 7 votes vote down vote up
/**
 * 发送html内容
 * */
@GetMapping("/sendHtmlMail")
public String sendHtmlMail(){
    MimeMessage message=null;
    try{

        message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(sendUser);
        helper.setTo("[email protected]");
        helper.setSubject("主题邮件");
        StringBuilder sb=new StringBuilder();
        sb.append("<h1>尊敬的客户您好!</h1>")
                .append("<p>欢迎您访问我的博客 www.fishpro.com.cn</p>");
        helper.setText(sb.toString(),true);
    }catch (Exception e){
        e.printStackTrace();
        return "fail";
    }
    mailSender.send(message);
    return "success";
}
 
Example #3
Source File: MailService.java    From SpringBoot-Course with MIT License 7 votes vote down vote up
/**
 * 发送带附件的邮件
 * @param to
 * @param subject
 * @param content
 * @param filePathList
 * @throws MessagingException
 */
public void sendAttachmentMail(String to, String subject, String content, String[] filePathList) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);

    for (String filePath: filePathList) {
        System.out.println(filePath);

        FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
        String fileName = fileSystemResource.getFilename();
        helper.addAttachment(fileName, fileSystemResource);
    }

    javaMailSender.send(message);
}
 
Example #4
Source File: EmailServiceImpl.java    From graviteeio-access-management with Apache License 2.0 7 votes vote down vote up
private String addResourcesInMessage(final MimeMessageHelper mailMessage, final String htmlText) throws Exception {
    final Document document = Jsoup.parse(htmlText);

    final List<String> resources = new ArrayList<>();

    final Elements imageElements = document.getElementsByTag("img");
    resources.addAll(imageElements.stream()
            .filter(imageElement -> imageElement.hasAttr("src"))
            .filter(imageElement -> !imageElement.attr("src").startsWith("http"))
            .map(imageElement -> {
                final String src = imageElement.attr("src");
                imageElement.attr("src", "cid:" + src);
                return src;
            })
            .collect(Collectors.toList()));

    final String html = document.html();
    mailMessage.setText(html, true);

    for (final String res : resources) {
        final FileSystemResource templateResource = new FileSystemResource(new File(templatesPath, res));
        mailMessage.addInline(res, templateResource, getContentTypeByFileName(res));
    }

    return html;
}
 
Example #5
Source File: MailService.java    From tutorials with MIT License 7 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #6
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 7 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param rscPath 静态资源地址
 * @param rscId   静态资源id
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId, res);

    mailSender.send(message);
}
 
Example #7
Source File: MailTool.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 7 votes vote down vote up
@SneakyThrows
public void sendHtml(String subjct, String text, String... to) {
	MimeMessage mimeMessage = mailSender.createMimeMessage();

	MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

	messageHelper.setFrom(from);
	messageHelper.setTo(to);
	messageHelper.setSubject(subjct);

	// html格式,第二个参数为true
	messageHelper.setText(text, true);

	// 附件
	// messageHelper.addAttachment

	jmsTool.sendMessage(JMSType.SEND_MAIL, mimeMessage);
}
 
Example #8
Source File: MailService.java    From flair-engine with Apache License 2.0 7 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #9
Source File: MailService.java    From Spring-5.0-Projects with MIT License 7 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #10
Source File: EmailController.java    From SpringAll with MIT License 6 votes vote down vote up
@RequestMapping("sendHtmlEmail")
public String sendHtmlEmail() {
	MimeMessage message = null;
	try {
		message = jms.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(from); 
		helper.setTo("[email protected]"); // 接收地址
		helper.setSubject("一封HTML格式的邮件"); // 标题
		// 带HTML格式的内容
		StringBuffer sb = new StringBuffer("<p style='color:#42b983'>使用Spring Boot发送HTML格式邮件。</p>");
		helper.setText(sb.toString(), true);
		jms.send(message);
		return "发送成功";
	} catch (Exception e) {
		e.printStackTrace();
		return e.getMessage();
	}
}
 
Example #11
Source File: EmailService.java    From jakduk-api with MIT License 6 votes vote down vote up
public void sendBulk(EmailPayload emailPayload) throws MessagingException {

		// Prepare the evaluation context
		final Context ctx = new Context(emailPayload.getLocale());
		ctx.setVariables(emailPayload.getBody());

		// Prepare message using a Spring helper
		final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
		final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

		message.setSubject(emailPayload.getSubject());
		message.setTo(emailPayload.getRecipientEmail());

		// Create the HTML body using Thymeleaf
		final String htmlContent = this.htmlTemplateEngine.process(emailPayload.getTemplateName(), ctx);
		message.setText(htmlContent, true /* isHtml */);

		// Send email
		this.mailSender.send(mimeMessage);
	}
 
Example #12
Source File: MailService.java    From pacbot with 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 #13
Source File: MailComposerImpl.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
/**
 * Add inline resource to mail message.
 * Resource id will be interpreted as file name in following fashion: filename_ext.
 *
 * @param helper          MimeMessageHelper, that has mail message
 * @param mail            html message template
 *
 * @throws javax.mail.MessagingException in case if resource can not be inlined
 */
void inlineResources(final MimeMessageHelper helper,
                     final Mail mail) throws MessagingException {

    if (CollectionUtils.isNotEmpty(mail.getParts())) {
        for (final MailPart part : mail.getParts()) {
            final String fileName = part.getFilename();
            final String resourceId = part.getResourceId();
            if (resourceId.startsWith(ATTACHMENT_PREFIX)) {
                final Pair<String, String> contentTypeAndFile = convertAttachmentKeyIntoContentTypeAndFilename(resourceId);
                if (contentTypeAndFile != null) {
                    helper.addAttachment(part.getFilename(), new ByteArrayResource(part.getData()), contentTypeAndFile.getFirst());
                }
            } else {
                helper.addInline(resourceId, new ByteArrayResource(part.getData()) {
                    @Override
                    public String getFilename() {
                        return fileName;
                    }
                });
            }
        }
    }

}
 
Example #14
Source File: SlaCheckerEmailService.java    From mojito with Apache License 2.0 6 votes vote down vote up
void sendEmail(long incidentId, String message) {
    MimeMessage mailMessage = emailSender.createMimeMessage();

    try {
        mailMessage.setSubject(getSubject(incidentId), StandardCharsets.UTF_8.toString());

        MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, StandardCharsets.UTF_8.toString());
        helper.setFrom(slaCheckerEmailConfig.getFrom());
        helper.setTo(slaCheckerEmailConfig.getTo());
        helper.setText(message, true);

        emailSender.send(mailMessage);
    } catch (Exception ex) {
        logger.error("Can't send OOSLA email", ex);
    }
}
 
Example #15
Source File: MailSender.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 发送html邮件
 */
public void sendHtmlMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setFrom(this.getFrom());
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("发送邮件异常! from: " + name+ "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example #16
Source File: Reporter.java    From jandy with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendMail(User user, Build current) throws MessagingException {
  mailSender.send(msg -> {
    GHUser ghUser = null;
    if (current.getCommit() != null)
      ghUser = github.getUser(current.getCommit().getCommitterName());

    PrettyTime p = new PrettyTime(Locale.ENGLISH);
    if (current.getFinishedAt() != null)
      current.setBuildAt(p.format(DatatypeConverter.parseDateTime(current.getFinishedAt())));

    HashMap<String, Object> model = new HashMap<>();
    model.put("project", current.getBranch().getProject());
    model.put("build", current);
    model.put("committerAvatarUrl", ghUser == null ? null : user.getAvatarUrl());

    MimeMessageHelper h = new MimeMessageHelper(msg, false, "UTF-8");
    h.setFrom("[email protected]");
    h.setTo(user.getEmail());
    h.setSubject("Jandy Performance Report");
    h.setText(FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate("email.ftl"), model), true);


  });
}
 
Example #17
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param rscPath 静态资源地址
 * @param rscId   静态资源id
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId, res);

    mailSender.send(message);
}
 
Example #18
Source File: MailService.java    From tutorials with MIT License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #19
Source File: EmailServiceImpl.java    From piggymetrics with MIT License 6 votes vote down vote up
@Override
@CatAnnotation
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {

	final String subject = env.getProperty(type.getSubject());
	final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());

	MimeMessage message = mailSender.createMimeMessage();

	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	helper.setTo(recipient.getEmail());
	helper.setSubject(subject);
	helper.setText(text);

	if (StringUtils.hasLength(attachment)) {
		helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
	}

	mailSender.send(message);
	log.info("{} email notification has been send to {}", type, recipient.getEmail());
}
 
Example #20
Source File: WebEmail.java    From Autumn with GNU General Public License v2.0 6 votes vote down vote up
public int sendHtmlEmail(String subject, String content, String to) {

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            mimeMessage.setContent(content, "text/html;charset=utf-8");
            messageHelper.setFrom(mailMessage.getFrom());
            messageHelper.setSubject(subject); //主题
            messageHelper.setTo(to); //发送给
            messageHelper.setCc(mailMessage.getFrom()); //抄送

            mailSender.send(mimeMessage);    //发送邮件

        } catch (Exception e) {
            logger.error("the email send error ! content: {}, exception: {}", content, e);
            return -1;
        }finally {
        }
        return 1;
    }
 
Example #21
Source File: MailService.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
/**
 * 发送html格式的邮件 
 * @param toMail
 * @param subject
 * @param content
 */
public void sendHtmlMail(String toMail,String subject,String content) {
	MimeMessage createMimeMessage = sender.createMimeMessage();
	
	try {
		//true表示需要创建一个multipart message 如何不设置就不会解析html
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(createMimeMessage,true);
		mimeMessageHelper.setFrom(formMail);
		mimeMessageHelper.setTo(toMail);
		mimeMessageHelper.setSubject(subject);
		mimeMessageHelper.setText(content, true);
		sender.send(createMimeMessage);
		logger.info("发送给"+toMail+"html邮件已经发送。 subject:"+subject);
	} catch (MessagingException e) {
		logger.info("发送给"+toMail+"html send mail error subject:"+subject);
		e.printStackTrace();
		
	}
}
 
Example #22
Source File: SendRegisterNotificationTask.java    From dubai with 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 #23
Source File: SpringMailService.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 发送附件
 *
 * @param to
 * @param subject
 * @throws javax.mail.MessagingException
 */
public void sendMailWithAttachment(String from ,String[] to, String subject) throws MessagingException {

    MimeMessage message = mailSender.createMimeMessage();
    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.toString());
    helper.addAttachment("show_name.jpg", new FileSystemResource(new File("d:/email.jpg")));

    /**
     *邮件内容
     */
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText("my text", true);


    mailSender.send(message);
}
 
Example #24
Source File: EmailServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private String addResourcesInMessage(final MimeMessageHelper mailMessage, final String htmlText) throws Exception {
    final Document document = Jsoup.parse(htmlText);

    final List<String> resources = new ArrayList<>();

    final Elements imageElements = document.getElementsByTag("img");
    resources.addAll(imageElements.stream()
            .filter(imageElement -> imageElement.hasAttr("src"))
            .filter(imageElement -> !imageElement.attr("src").startsWith("http"))
            .map(imageElement -> {
                final String src = imageElement.attr("src");
                imageElement.attr("src", "cid:" + src);
                return src;
            })
            .collect(Collectors.toList()));

    final String html = document.html();
    mailMessage.setText(html, true);

    for (final String res : resources) {
        final FileSystemResource templateResource = new FileSystemResource(new File(templatesPath, res));
        mailMessage.addInline(res, templateResource, getContentTypeByFileName(res));
    }

    return html;
}
 
Example #25
Source File: MailServiceImpl.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
@Override
public void sendTemplateMail(Mail mail) throws MessagingException {
    checkMail(mail);
    // templateEngine 替换掉动态参数,生产出最后的html
    String emailContent = templateEngine.process(mail.getEmailTemplateName(), mail.getEmailTemplateContext());

    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(sender);
    helper.setTo(mail.getReceiver());
    helper.setSubject(mail.getSubject());
    helper.setText(emailContent, true);
    mailSender.send(mimeMessage);
    saveMail(mail);
}
 
Example #26
Source File: MailService.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #27
Source File: MailService.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
public void sendAttachmentsMail(String toMail,String subject,String content,String filePath) {
 	MimeMessage message = sender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(formMail);
        helper.setTo(toMail);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = filePath.substring(filePath.lastIndexOf("/"));
        helper.addAttachment(fileName, file);
        sender.send(message);
        logger.info("发送给"+toMail+"带附件的邮件已经发送。");
    } catch (MessagingException e) {
        e.printStackTrace();
        logger.error("发送给"+toMail+"带附件的邮件时发生异常!", e);
    }
}
 
Example #28
Source File: SpitterMailServiceImpl.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
* <p>描述:采用Velocity模板的富文本email</p>
* @param to
* @param spittle
* @throws MessagingException
 */
public void sendRichEmailWithVelocity(String to, Spittle spittle) throws MessagingException {
	MimeMessage message = mailSender.createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	String spitterName = spittle.getSpitter().getFullName();
	helper.setFrom("[email protected]");
	helper.setTo(to);
	helper.setSubject("New spittle from " + spitterName);
	
	Map<String, Object> model = new HashMap<String, Object>();
	model.put("spitterName", spitterName);
	model.put("spittleText", spittle.getText());
	String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
			"emailTemplate.vm", "UTF-8", model);
	
	helper.setText(emailText, true);
	ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.jpg");
	helper.addInline("spitterLogo", couponImage);
	mailSender.send(message);
}
 
Example #29
Source File: MailController.java    From spring-boot-study with Apache License 2.0 6 votes vote down vote up
/**
 * 内联附件的邮件测试
 *
 * @return success
 * @throws MessagingException
 */
@GetMapping("/freemarker")
public String freemarker() throws MessagingException, IOException, TemplateException {
    MimeMessage message = this.javaMailSender.createMimeMessage();
    // 第二个参数表示是否开启multipart模式
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
    messageHelper.setFrom(this.mailProperties.getUsername());
    messageHelper.setTo("[email protected]");
    messageHelper.setSubject("基于freemarker模板的邮件测试");

    Map<String, Object> model = new HashMap<>();
    model.put("username", "itmuch");
    model.put("event", "IT牧场大事件");

    String content = FreeMarkerTemplateUtils.processTemplateIntoString(
            this.freemarkerConfiguration.getTemplate("mail.ftl"), model);

    // 第二个参数表示是否html,设为true
    messageHelper.setText(content, true);

    this.javaMailSender.send(message);
    return "success";
}
 
Example #30
Source File: MailService.java    From JDeSurvey with 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);
   }