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

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper#setTo() . 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: 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 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 '{}'", to, e);
    }
}
 
Example 2
Source File: MailSender.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 */
public void sendAttachmentMail(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.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        throw new RuntimeException("发送邮件异常! from: " + name + "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example 3
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 4
Source File: MailService.java    From TASK-Management-System with MIT License 6 votes vote down vote up
public boolean sendMail(String to, String text, String subject, String res) throws MessagingException {
  MimeMessage message = mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(message,true);
  try {
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);
    ClassPathResource file = new ClassPathResource(res);
    helper.addAttachment(res, file);
  } catch (MessagingException e) {
    e.printStackTrace();
    return false;
  }
  mailSender.send(message);
  return true;
}
 
Example 5
Source File: EmailService.java    From jcart with MIT License 6 votes vote down vote up
public void sendEmail(String to, String subject, String content)
{
       try
	{
       	// Prepare message using a Spring helper
           final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
           final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
           message.setSubject(subject);
           message.setFrom(supportEmail);
           message.setTo(to);
           message.setText(content, true /* isHtml */);
           
		javaMailSender.send(message.getMimeMessage());
	} 
       catch (MailException | MessagingException e)
	{
       	logger.error(e);
		throw new JCartException("Unable to send email");
	}
}
 
Example 6
Source File: MailServiceImpl.java    From Java-API-Test-Examples with Apache License 2.0 6 votes vote down vote up
/**
 * 发送正文中有静态资源(图片)的邮件
 * @param to
 * @param subject
 * @param content
 * @param rscPath
 * @param rscId
 */
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
    MimeMessage message = mailSender.createMimeMessage();

    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource res = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, res);

        mailSender.send(message);
        log.info("嵌入静态资源的邮件已经发送。");
    } catch (MessagingException e) {
        log.error("发送嵌入静态资源的邮件时发生异常!", e);
    }
}
 
Example 7
Source File: MailService.java    From angularjs-springboot-bookstore 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 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 8
Source File: MailService.java    From jhipster-microservices-example 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 9
Source File: MailServiceImpl.java    From Jantent with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to
 * @param subject
 * @param content
 * @param filepath
 */
@Override
public void sendFileMail(String to, String subject, String content, String filepath) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setFrom(mailFrom);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);

        FileSystemResource file = new FileSystemResource(new File(filepath));
        String fileName = filepath.substring(filepath.lastIndexOf(File.separator));
        helper.addAttachment(fileName,file);

        mailSender.send(mimeMessage);

    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 10
Source File: EmailController.java    From SpringAll with MIT License 6 votes vote down vote up
@RequestMapping("sendInlineMail")
public String sendInlineMail() {
	MimeMessage message = null;
	try {
		message = jms.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(from); 
		helper.setTo("[email protected]"); // 接收地址
		helper.setSubject("一封带静态资源的邮件"); // 标题
		helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容
		// 传入附件
		FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
           helper.addInline("img", file); 
           jms.send(message);
		return "发送成功";
	} catch (Exception e) {
		e.printStackTrace();
		return e.getMessage();
	}
}
 
Example 11
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 12
Source File: MailServiceImpl.java    From DouBiNovel with Apache License 2.0 6 votes vote down vote up
@Override
public void sendHtmlMail(String to, String subject, String content) {
    MimeMessage message = mailSender.createMimeMessage();

    try {
        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
        logger.info("html邮件发送成功");
    } catch (MessagingException e) {
        logger.error("发送html邮件时发生异常!", e);
    }
}
 
Example 13
Source File: EmailServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Email email, User user, Client client) {
    if (enabled) {
        try {
            final MimeMessageHelper mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, StandardCharsets.UTF_8.name());
            final Template template = freemarkerConfiguration.getTemplate(email.getTemplate());
            final Template plainTextTemplate = new Template("subject", new StringReader(email.getSubject()), freemarkerConfiguration);

            // compute email subject
            final String subject = processTemplateIntoString(plainTextTemplate, email.getParams());
            // compute email content
            final String content = processTemplateIntoString(template, email.getParams());
            final String from = email.getFrom();

            String fromName = email.getFromName();
            if (fromName == null || fromName.isEmpty()) {
                mailMessage.setFrom(from);
            } else {
                mailMessage.setFrom(from, fromName);
            }

            mailMessage.setTo(email.getTo());
            mailMessage.setSubject(subject);

            final String html = addResourcesInMessage(mailMessage, content);
            LOGGER.debug("Sending an email to: {}\nSubject: {}\nMessage: {}", email.getTo(), email.getSubject(), html);
            mailSender.send(mailMessage.getMimeMessage());
            auditService.report(AuditBuilder.builder(EmailAuditBuilder.class).domain(domain.getId()).client(client).email(email).user(user));
        } catch (final Exception ex) {
            LOGGER.error("Error while sending email", ex);
            new TechnicalManagementException("Error while sending email", ex);
            auditService.report(AuditBuilder.builder(EmailAuditBuilder.class).domain(domain.getId()).client(client).email(email).throwable(ex));
        }
    }
}
 
Example 14
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 15
Source File: MailService.java    From JDeSurvey with 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 16
Source File: FrameWorkMailSender.java    From framework with Apache License 2.0 5 votes vote down vote up
@Override
public void doWork(Mail task) throws Exception {
    if (task != null) {
        MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject(task.getTitle());
        mimeMessageHelper.setTo(task.getTo());
        mimeMessageHelper.setText(task.getContent());
        this.javaMailSender.send(mimeMessage);
    }
}
 
Example 17
Source File: NewUserEmailTransformer.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 18
Source File: MailComposerImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
void composeMessage(final MimeMessage message,
                    final String shopCode,
                    final String locale,
                    final List<String> mailTemplateChain,
                    final String templateName,
                    final String from,
                    final String toEmail,
                    final String ccEmail,
                    final String bccEmail,
                    final Map<String, Object> model)
        throws MessagingException, IOException, ClassNotFoundException {


    final MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

    helper.setTo(toEmail);

    helper.setSentDate(new Date());

    if (ccEmail != null) {
        helper.setCc(ccEmail);
    }

    if (bccEmail != null) {
        helper.setBcc(bccEmail);
    }


    final String textContent = processTemplate(mailTemplateChain, shopCode, locale, templateName, ".txt", model);
    final String htmlContent = processTemplate(mailTemplateChain, shopCode, locale, templateName, ".html", model);
    final String propString = processTemplate(mailTemplateChain, shopCode, locale, templateName, ".properties", model);
    final Properties prop = new Properties();
    if (propString != null) {
        prop.load(new StringReader(propString));
    }
    helper.setSubject(prop.getProperty("subject"));

    if (from == null) {
        helper.setFrom(prop.getProperty("from"));
    } else {
        helper.setFrom(from);
    }

    final Map<String, byte[]> attachments = collectAttachments(model);

    composeMessage(helper, textContent, htmlContent, attachments, mailTemplateChain, shopCode, locale, templateName);

}
 
Example 19
Source File: EmailUtil.java    From SpringBoot-Home with Apache License 2.0 4 votes vote down vote up
/**
 * 构建复杂邮件信息类
 * @param mail
 * @throws MessagingException
 */
public void sendMail(MailDomain mail) throws MessagingException {

    //true表示支持复杂类型
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
    //邮件发信人从配置项读取
    mail.setSender(sender);
    //邮件发信人
    messageHelper.setFrom(mail.getSender());
    //邮件收信人
    messageHelper.setTo(mail.getReceiver().split(","));
    //邮件主题
    messageHelper.setSubject(mail.getSubject());
    //邮件内容
    if (mail.getIsTemplate()) {
        // templateEngine 替换掉动态参数,生产出最后的html
        String emailContent = templateEngine.process(mail.getEmailTemplateName(), mail.getEmailTemplateContext());
        messageHelper.setText(emailContent, true);
    }else {
        messageHelper.setText(mail.getText());
    }
    //抄送
    if (!StringUtils.isEmpty(mail.getCc())) {
        messageHelper.setCc(mail.getCc().split(","));
    }
    //密送
    if (!StringUtils.isEmpty(mail.getBcc())) {
        messageHelper.setCc(mail.getBcc().split(","));
    }
    //添加邮件附件
    if (mail.getFilePath() != null) {
        File file = new File(mail.getFilePath());
        messageHelper.addAttachment(file.getName(), file);
    }
    //发送时间
    if (StringUtils.isEmpty(mail.getSentDate())) {
        messageHelper.setSentDate(mail.getSentDate());
    }
    //正式发送邮件
    mailSender.send(messageHelper.getMimeMessage());
}
 
Example 20
Source File: EmailJobAlarm.java    From xxl-job with GNU General Public License v3.0 4 votes vote down vote up
/**
 * fail alarm
 *
 * @param jobLog
 */
public boolean doAlarm(XxlJobInfo info, XxlJobLog 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
        XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
        String personal = I18nUtil.getString("admin_name_full");
        String title = I18nUtil.getString("jobconf_monitor");
        String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
                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 = XxlJobAdminConfig.getAdminConfig().getMailSender().createMimeMessage();

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

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

                alarmResult = false;
            }

        }
    }

    return alarmResult;
}