Java Code Examples for org.springframework.mail.javamail.MimeMessageHelper#setText()

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper#setText() . 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 gravitee-management-rest-api 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 2
Source File: DefaultEmailSender.java    From web-flash with MIT License 6 votes vote down vote up
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        if(StringUtil.isNotEmpty(cc)) {
            helper.setCc(cc);
        }
        helper.setSubject(title);
        helper.setText(content, true);
        if(inputStreamSource!=null) {
            helper.addAttachment(attachmentFilename, inputStreamSource);
        }
        javaMailSender.send(message);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 3
Source File: MailService.java    From alchemy 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, 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 4
Source File: EmailController.java    From SpringAll with MIT License 6 votes vote down vote up
@RequestMapping("sendAttachmentsMail")
public String sendAttachmentsMail() {
	MimeMessage message = null;
	try {
		message = jms.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(from); 
		helper.setTo("[email protected]"); // 接收地址
		helper.setSubject("一封带附件的邮件"); // 标题
		helper.setText("详情参见附件内容!"); // 内容
		// 传入附件
		FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/项目文档.docx"));
           helper.addAttachment("项目文档.docx", file);
           jms.send(message);
		return "发送成功";
	} catch (Exception e) {
		e.printStackTrace();
		return e.getMessage();
	}
}
 
Example 5
Source File: MailService.java    From ServiceCutter 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 e-mail[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(from);
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example 6
Source File: RegisterSystemListener.java    From cms with 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 7
Source File: SendMailServiceImpl.java    From cloud-service with MIT License 6 votes vote down vote up
/**
 * 发送邮件
 *
 * @param toUser  收件人邮件地址
 * @param subject 标题
 * @param text    正文
 * @return
 */
@Override
public boolean sendMail(String toUser, String subject, String text) {
	try {
		MimeMessage message = javaMailSender.createMimeMessage();

		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(serverMail);
		helper.setTo(toUser);
		helper.setSubject(subject);
		helper.setText(text, true);

		javaMailSender.send(message);

		log.info("发送邮件to:{},主题:{},内容:{}", toUser, subject, text);
	} catch (Exception e) {
		log.error("", e);

		return Boolean.FALSE;
	}

	return Boolean.TRUE;

}
 
Example 8
Source File: MailService.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[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 e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example 9
Source File: MailService.java    From expper with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[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.getMailgun().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example 10
Source File: ActivateUserEmailTransformer.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@Transformer
public MimeMessage transform(final User user) throws MessagingException, IOException {
	MimeMessage message = getEmailSender().createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message);
	helper.setTo(user.getEmail());
	helper.setFrom(getDefaultFromAddress(), getDefaultFromName());
	helper.setReplyTo(getDefaultFromAddress());
	helper.setSubject(getSubject());
	Map<String, Object> model = buildModel(user);
	helper.setText(getText(model), true);
	return message;
}
 
Example 11
Source File: JavaMailUtils.java    From seppb with MIT License 5 votes vote down vote up
public Boolean call() {
    int times = 0;
    boolean isSuccess = false;
    while (times <= mailDTO.getFailRetryCount()) {
        try {
            sendMail(javaMailSender, mimeMessage);
            isSuccess = true;
            break;
        } catch (Exception e) {
            log.error("邮件发送给{}失败{}", mailDTO.getTo(), e);
            try {
                if (times >= mailDTO.getFailRetryCount()) {
                    MimeMessage mimeMessageNew = javaMailSender.createMimeMessage();
                    MimeMessageHelper helperRetry = new MimeMessageHelper(mimeMessageNew, true);
                    helperRetry.setFrom(mailDTO.getFrom());
                    helperRetry.setTo(mailDTO.getFailTo());
                    helperRetry.setSubject(mailDTO.getFailSubject());
                    String[] to = mailDTO.getTo();
                    helperRetry.setText(String.format(WARNING_RETRY_ERROR, to), false);
                    sendMail(javaMailSender, mimeMessageNew);
                }
                times++;
                Thread.sleep(mailDTO.getFailRetryTime());
            } catch (Exception ex) {
                times++;
                log.error("邮件重试发送失败{}", e);
            }
        }
    }
    return isSuccess;
}
 
Example 12
Source File: EmailJob.java    From quartz-manager with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void sendEmail(JobDataMap map) {
	String subject 	   = map.getString("subject");
	String messageBody = map.getString("messageBody");
	List<String> to    = (List<String>) map.get("to");
	List<String> cc	   = (List<String>) map.get("cc");
	List<String> bcc   = (List<String>) map.get("bcc");
	
	MimeMessage message = mailSender.createMimeMessage();

	try {
		MimeMessageHelper helper = new MimeMessageHelper(message, false);
		for(String receipient : to) {
			helper.setFrom("[email protected]", "Julius from Dynamic Quartz");
			helper.setTo(receipient);
			helper.setSubject(subject);
			helper.setText(messageBody);
			if(!isEmpty(cc))
				helper.setCc(cc.stream().toArray(String[]::new));
			if(!isEmpty(bcc))
				helper.setBcc(bcc.stream().toArray(String[]::new));
			mailSender.send(message);
		}
	} catch (MessagingException | UnsupportedEncodingException e) {
		log.error("An error occurred: {}", e.getLocalizedMessage());
	}
}
 
Example 13
Source File: SmtpMailer.java    From alf.io with 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 14
Source File: SpringBootMailServiceImpl.java    From springBoot with MIT License 5 votes vote down vote up
@Override
public void sendAttachmentsMail(String to, String subject, String content, List<File> files) 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);
    //添加附件
    for(File file : files){
        helper.addAttachment(file.getName(), new FileSystemResource(file));
    }

    mailSender.send(message);
}
 
Example 15
Source File: MailController.java    From spring-boot-study with MIT License 5 votes vote down vote up
/**
 * 发送附件内容
 * */
@GetMapping("/sendAttachMail")
public String sendAttachMail(){
    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);
        //获取附件资源
        FileSystemResource fileSystemResource =new FileSystemResource(new File(""));
        //把附件资源加入到发送消息中
        helper.addAttachment("",fileSystemResource);

    }catch (Exception e){
        e.printStackTrace();
        return "fail";
    }
    mailSender.send(message);
    return "success";
}
 
Example 16
Source File: MailServiceImpl.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
@Override
public void sendAttachmentsMail(Mail mail) throws MessagingException {
    checkMail(mail);
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(sender);
    helper.setTo(mail.getReceiver());
    helper.setSubject(mail.getSubject());
    helper.setText(mail.getText());
    File file = new File(mail.getFilePath());
    helper.addAttachment(file.getName(), file);
    mailSender.send(mimeMessage);
    saveMail(mail);
}
 
Example 17
Source File: LicencePurchaseEmailTransformer.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@Transformer
public MimeMessage transform(final LicencePurchaseEmail licencePurchaseEmail) throws MessagingException, IOException {
	MimeMessage message = getEmailSender().createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message);
	helper.setTo(licencePurchaseEmail.getUser().getEmail());
	helper.setFrom(getDefaultFromAddress(), getDefaultFromName());
	helper.setReplyTo(getDefaultFromAddress());
	helper.setSubject(getSubject());
	Map<String, Object> model = buildModel(licencePurchaseEmail);
	helper.setText(getText(model), true);
	return message;
}
 
Example 18
Source File: PaperightCreditTransactionPaymentReceivedEmailTransformer.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@Transformer
   public MimeMessage transform(final PaperightCreditTransaction transaction) throws MessagingException, IOException {
	MimeMessage message = getEmailSender().createMimeMessage();
   	MimeMessageHelper helper = new MimeMessageHelper(message);
   	helper.setTo(transaction.getUser().getEmail());
   	helper.setFrom(getDefaultFromAddress(), getDefaultFromName());
   	helper.setReplyTo(getDefaultFromAddress());
   	helper.setSubject(getSubject());
   	Map<String, Object> model = buildModel(transaction);
   	helper.setText(getText(model), true);
   	return message;
}
 
Example 19
Source File: JobFailMonitorHelper.java    From datax-web with MIT License 4 votes vote down vote up
/**
 * fail alarm
 *
 * @param jobLog
 */
private boolean failAlarm(JobInfo info, JobLog jobLog){
	boolean alarmResult = true;

	// send monitor email
	if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {

		// alarmContent
		String alarmContent = "Alarm Job LogId=" + jobLog.getId();
		if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
			alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
		}
		if (jobLog.getHandleCode()>0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
			alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
		}

		// email info
		JobGroup group = JobAdminConfig.getAdminConfig().getJobGroupMapper().load(Integer.valueOf(info.getJobGroup()));
		String personal = I18nUtil.getString("admin_name_full");
		String title = I18nUtil.getString("jobconf_monitor");
		String content = MessageFormat.format(mailBodyTemplate,
				group!=null?group.getTitle():"null",
				info.getId(),
				info.getJobDesc(),
				alarmContent);

		Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
		for (String email: emailSet) {

			// make mail
			try {
				MimeMessage mimeMessage = JobAdminConfig.getAdminConfig().getMailSender().createMimeMessage();

				MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
				helper.setFrom(JobAdminConfig.getAdminConfig().getEmailUserName(), personal);
				helper.setTo(email);
				helper.setSubject(title);
				helper.setText(content, true);

				JobAdminConfig.getAdminConfig().getMailSender().send(mimeMessage);
			} catch (Exception e) {
				logger.error(">>>>>>>>>>> datax-web, job fail alarm email send error, JobLogId:{}", jobLog.getId(), e);

				alarmResult = false;
			}

		}
	}

	// do something, custom alarm strategy, such as sms


	return alarmResult;
}
 
Example 20
Source File: EmailService.java    From guardedbox with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Sends an email.
 *
 * @param to Receiver.
 * @param subject Subject.
 * @param content HTML Content.
 */
public void send(
        String to,
        String subject,
        String content) {

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

    try {

        if (!StringUtils.isEmpty(mailFrom))
            mimeMessageHelper.setFrom(mailFrom);

        mimeMessageHelper.setTo(to);

        if (!StringUtils.isEmpty(mailBcc))
            mimeMessageHelper.setBcc(mailBcc);

        mimeMessageHelper.setSubject(subject);

        mimeMessageHelper.setText(content, true);

    } catch (MessagingException e) {
        throw new MailSendException("Error setting the email attributes", e);
    }

    javaMailSender.send(mimeMessage);

}