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

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper#addAttachment() . 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: 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 3
Source File: SpringJavaEmailSender.java    From DataSphereStudio with Apache License 2.0 7 votes vote down vote up
private MimeMessage parseToMimeMessage(Email email) {
    MimeMessage message = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        if(StringUtils.isBlank(email.getFrom())) {
            messageHelper.setFrom(SendEmailAppJointConfiguration.DEFAULT_EMAIL_FROM().getValue());
        } else {
            messageHelper.setFrom(email.getFrom());
        }
        messageHelper.setSubject(email.getSubject());
        messageHelper.setTo(email.getTo());
        messageHelper.setCc(email.getCc());
        messageHelper.setBcc(email.getBcc());
        for(Attachment attachment: email.getAttachments()){
            messageHelper.addAttachment(attachment.getName(), new ByteArrayDataSource(attachment.getBase64Str(), attachment.getMediaType()));
        }
        messageHelper.setText(email.getContent(), true);
    } catch (Exception e) {
        logger.error("Send mail failed", e);
    }
    return message;
}
 
Example 4
Source File: MailTests.java    From SpringBootUnity with MIT License 6 votes vote down vote up
@Test
public void sendAttachmentsMail() throws Exception {

    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setSubject("主题:有附件");
    helper.setText("有附件的邮件");

    FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
    helper.addAttachment("附件-1.jpg", file);
    helper.addAttachment("附件-2.jpg", file);

    mailSender.send(mimeMessage);
}
 
Example 5
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 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 filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        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 file = new FileSystemResource(new File(filePath));
//            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
			File file = new File(filePath);
			//获取文件名
            String fileName = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/")+1);
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            log.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常!", e);
        }
    }
 
Example 7
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 8
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, 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 file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example 9
Source File: MailServiceImpl.java    From olat with 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 10
Source File: DefaultEmailSender.java    From flash-waimai 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(StringUtils.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 11
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 12
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, 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 file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example 13
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 14
Source File: DemoController.java    From seed with Apache License 2.0 5 votes vote down vote up
@GetMapping("/mail")
public CommResult mail(){
    //发送一封简单的邮件
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(this.mailFrom);
    simpleMailMessage.setTo("[email protected]");
    simpleMailMessage.setSubject("下午开会准时参加");
    simpleMailMessage.setText("15点26楼会议室");
    this.javaMailSender.send(simpleMailMessage);
    //发送一封复杂的邮件
    //注意addInline()里面的"huiyi"要与"cid:huiyi"一致
    //注意addAttachment()方法用于添加附件
    try{
        MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(this.mailFrom);
        helper.setTo("[email protected]");
        helper.setSubject("请查收会议纪要");
        helper.setText("<html><body><span style='color:#F00'>会议截图如下,完整图片见附件。</span><br><img src=\\\"cid:huiyi\\\" ></body></html>", true);
        helper.addInline("huiyi", new FileSystemResource(new File("E:\\Jadyer\\Stripes.jpg")));
        helper.addAttachment("会议纪要完整图片.jpg", new FileSystemResource(new File("E:\\Jadyer\\Fedora13.jpg")));
        this.javaMailSender.send(mimeMessage);
    }catch(MessagingException e){
        return CommResult.fail(CodeEnum.SYSTEM_BUSY.getCode(), "邮件发送失败,堆栈轨迹如下:"+ JadyerUtil.extractStackTrace(e));
    }
    return CommResult.success();
}
 
Example 15
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 16
Source File: MailController.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
@PostMapping("/sendAttachments")
  public String sendAttachmentsMail(@RequestBody Mail mail) throws MessagingException  {

  	MimeMessage mimeMessage = mailSender.createMimeMessage();
  	MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  	helper.setFrom(mail.getSender());
  	helper.setTo(mail.getReceiver());
  	helper.setSubject(mail.getSubject());
  	helper.setText(mail.getText());
  	FileSystemResource file = new FileSystemResource(new File("1.png"));
  	helper.addAttachment("附件.jpg", file);
  	mailSender.send(mimeMessage);
return "发送成功!";

  }
 
Example 17
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 18
Source File: WaltzEmailer.java    From waltz with 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 19
Source File: MailService.java    From tutorial with MIT License 5 votes vote down vote up
/**
 * 发送HTML格式,带有附件的邮件
 * @param to
 * @param subject
 * @param body
 * @param attachmentName
 * @param iss
 * @throws MessagingException
 */
public void sendHtmlEmailWithAttachment(String to, String subject, String body, String attachmentName, InputStreamSource iss) throws MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(sender);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(body, true);
    // 可以增加多个附件,每个附件调用addAttachement
    helper.addAttachment(attachmentName, iss);

    mailSender.send(mimeMessage);

}
 
Example 20
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());
}