/** * Add an attachment to the MimeMessage, taking the content from a * {@code java.io.File}. * <p>The content type will be determined by the name of the given * content file. Do not use this for temporary files with arbitrary * filenames (possibly ending in ".tmp" or the like)! * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param file the File resource to take the content from * @throws MessagingException in case of errors * @see #addAttachment(String, org.springframework.core.io.InputStreamSource) * @see #addAttachment(String, javax.activation.DataSource) */ public void addAttachment(String attachmentFilename, File file) throws MessagingException { Assert.notNull(file, "File must not be null"); FileDataSource dataSource = new FileDataSource(file); dataSource.setFileTypeMap(getFileTypeMap()); addAttachment(attachmentFilename, dataSource); }
/** * Add an attachment to the MimeMessage, taking the content from an * {@code org.springframework.core.io.InputStreamResource}. * <p>Note that the InputStream returned by the InputStreamSource * implementation needs to be a <i>fresh one on each call</i>, as * JavaMail will invoke {@code getInputStream()} multiple times. * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param inputStreamSource the resource to take the content from * (all of Spring's Resource implementations can be passed in here) * @param contentType the content type to use for the element * @throws MessagingException in case of errors * @see #addAttachment(String, java.io.File) * @see #addAttachment(String, javax.activation.DataSource) * @see org.springframework.core.io.Resource */ public void addAttachment( String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException { Assert.notNull(inputStreamSource, "InputStreamSource must not be null"); if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) { throw new IllegalArgumentException( "Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call."); } DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename); addAttachment(attachmentFilename, dataSource); }
/** * Add an attachment to the MimeMessage, taking the content from an * {@code org.springframework.core.io.InputStreamResource}. * <p>The content type will be determined by the given filename for * the attachment. Thus, any content source will be fine, including * temporary files with arbitrary filenames. * <p>Note that the InputStream returned by the InputStreamSource * implementation needs to be a <i>fresh one on each call</i>, as * JavaMail will invoke {@code getInputStream()} multiple times. * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param inputStreamSource the resource to take the content from * (all of Spring's Resource implementations can be passed in here) * @throws MessagingException in case of errors * @see #addAttachment(String, java.io.File) * @see #addAttachment(String, javax.activation.DataSource) * @see org.springframework.core.io.Resource */ public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) throws MessagingException { String contentType = getFileTypeMap().getContentType(attachmentFilename); addAttachment(attachmentFilename, inputStreamSource, contentType); }
/** * Add an attachment to the MimeMessage, taking the content from a * {@code java.io.File}. * <p>The content type will be determined by the name of the given * content file. Do not use this for temporary files with arbitrary * filenames (possibly ending in ".tmp" or the like)! * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param file the File resource to take the content from * @throws MessagingException in case of errors * @see #addAttachment(String, org.springframework.core.io.InputStreamSource) * @see #addAttachment(String, javax.activation.DataSource) */ public void addAttachment(String attachmentFilename, File file) throws MessagingException { Assert.notNull(file, "File must not be null"); FileDataSource dataSource = new FileDataSource(file); dataSource.setFileTypeMap(getFileTypeMap()); addAttachment(attachmentFilename, dataSource); }
/** * Add an attachment to the MimeMessage, taking the content from an * {@code org.springframework.core.io.InputStreamResource}. * <p>Note that the InputStream returned by the InputStreamSource * implementation needs to be a <i>fresh one on each call</i>, as * JavaMail will invoke {@code getInputStream()} multiple times. * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param inputStreamSource the resource to take the content from * (all of Spring's Resource implementations can be passed in here) * @param contentType the content type to use for the element * @throws MessagingException in case of errors * @see #addAttachment(String, java.io.File) * @see #addAttachment(String, javax.activation.DataSource) * @see org.springframework.core.io.Resource */ public void addAttachment( String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException { Assert.notNull(inputStreamSource, "InputStreamSource must not be null"); if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) { throw new IllegalArgumentException( "Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call."); } DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename); addAttachment(attachmentFilename, dataSource); }
/** * 发送带附件的邮件 * @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)); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } }
/** * Add an attachment to the MimeMessage, taking the content from an * {@code org.springframework.core.io.InputStreamResource}. * <p>The content type will be determined by the given filename for * the attachment. Thus, any content source will be fine, including * temporary files with arbitrary filenames. * <p>Note that the InputStream returned by the InputStreamSource * implementation needs to be a <i>fresh one on each call</i>, as * JavaMail will invoke {@code getInputStream()} multiple times. * @param attachmentFilename the name of the attachment as it will * appear in the mail * @param inputStreamSource the resource to take the content from * (all of Spring's Resource implementations can be passed in here) * @throws MessagingException in case of errors * @see #addAttachment(String, java.io.File) * @see #addAttachment(String, javax.activation.DataSource) * @see org.springframework.core.io.Resource */ public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) throws MessagingException { String contentType = getFileTypeMap().getContentType(attachmentFilename); addAttachment(attachmentFilename, inputStreamSource, contentType); }
@Override 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()); } }
@Override public void prepare(MimeMessage mimeMessage) throws Exception { EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType()); EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType()); boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments()); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding()); message.setTo(emailUser.getEmailAddress()); message.setFrom(info.getFromAddress()); message.setSubject(info.getSubject()); if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) { message.setBcc(emailUser.getBCCAddresses()); } if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) { message.setCc(emailUser.getCCAddresses()); } String messageBody = info.getMessageBody(); if (messageBody == null) { messageBody = buildMessageBody(info, props); } message.setText(messageBody, true); for (Attachment attachment : info.getAttachments()) { ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType()); message.addAttachment(attachment.getFilename(), dataSource); } } };
helper.setText("Spring Integration Rocks!"); helper.addAttachment(pictureName, byteArrayResource, "image/png");
@RequestMapping("/attchments") public void sendAttachmentsMail() throws Exception { logger.info("发送带附件的邮件..."); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom("576697722@qq.com"); helper.setTo("576697722@qq.com"); helper.setSubject("主题:有附件"); helper.setText("有附件的邮件"); FileSystemResource file = new FileSystemResource(new File("/static/img/logo.png")); helper.addAttachment("附件-1.jpg", file); helper.addAttachment("附件-2.jpg", file); mailSender.send(mimeMessage); }
private MailMessage createMailMessageFromByteArrayMessage(Message<byte[]> message) { Assert.state(this.mailSender instanceof JavaMailSender, "this adapter requires a 'JavaMailSender' to send a 'MimeMailMessage'"); String attachmentFileName = message.getHeaders().get(MailHeaders.ATTACHMENT_FILENAME, String.class); if (attachmentFileName == null) { throw new MessageMappingException(message, "Header '" + MailHeaders.ATTACHMENT_FILENAME + "' is required when mapping a Message with a byte array payload to a MailMessage."); } Integer multipartMode = message.getHeaders().get(MailHeaders.MULTIPART_MODE, Integer.class); if (multipartMode == null) { multipartMode = MimeMessageHelper.MULTIPART_MODE_MIXED; } MimeMessage mimeMessage = ((JavaMailSender) this.mailSender).createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipartMode); helper.addAttachment(attachmentFileName, new ByteArrayResource(message.getPayload())); return new MimeMailMessage(helper); } catch (MessagingException e) { throw new MessageMappingException(message, "failed to create MimeMessage", e); } }
private void sendMimeMail(MailVo mailVo) { try { MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型 mailVo.setFrom(getMailSendFrom());//邮件发信人从配置项读取 messageHelper.setFrom(mailVo.getFrom());//邮件发信人 messageHelper.setTo(mailVo.getTo().split(","));//邮件收信人 messageHelper.setSubject(mailVo.getSubject());//邮件主题 messageHelper.setText(mailVo.getText());//邮件内容 if (!StringUtils.isEmpty(mailVo.getCc())) {//抄送 messageHelper.setCc(mailVo.getCc().split(",")); } if (!StringUtils.isEmpty(mailVo.getBcc())) {//密送 messageHelper.setCc(mailVo.getBcc().split(",")); } if (mailVo.getMultipartFiles() != null) {//添加邮件附件 for (MultipartFile multipartFile : mailVo.getMultipartFiles()) { messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile); } } if (StringUtils.isEmpty(mailVo.getSentDate())) {//发送时间 mailVo.setSentDate(new Date()); messageHelper.setSentDate(mailVo.getSentDate()); } mailSender.send(messageHelper.getMimeMessage());//正式发送邮件 mailVo.setStatus("ok"); logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo()); } catch (Exception e) { throw new RuntimeException(e);//发送失败 } }
@Override public void attach(MimeMessageHelper mimeMessageHelper) throws MessagingException { mimeMessageHelper.addAttachment(filename, file); } }
JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here final byte[] data = .... this holds my PDF data mailSender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); // set from, to, subject using helper helper.addAttachment("my.pdf", new ByteArrayResource(data)); } });
InputStreamSource iss = new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { // provide fresh InputStream return new FileInputStream("c:\\a.txt"); } } MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); message.addAttachment("attachment", iss);
private void addOctetStreamAttachment(MimeMessageHelper helper, String fileName, byte[] data) throws MessagingException { helper.addAttachment(fileName + ".pgp", new ByteArrayResource(data), "application/octet-stream"); }
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); message.setTo(mail.getTo()); message.setFrom(mail.getFrom()); message.setSubject(mail.getSubject()); message.setText(mail.getText(), mail.getHtml()); if(StringUtils.isNotBlank(mail.getPdfAttachmentFileName())) { File file = new File(uploadDir + "/" + mail.getPdfAttachmentFileName()); DataSource dataSource = new ByteArrayDataSource(new FileInputStream(file), "application/pdf"); message.addAttachment(mail.getPdfAttachmentFileName(), dataSource); }
JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("mail.host.com"); MimeMessage message = sender.createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo("test@host.com"); helper.setText("Check out this image!"); // let's attach the infamous windows Sample file (this time copied to c:/) FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg")); helper.addAttachment("CoolImage.jpg", file); sender.send(message);
ByteArrayDataSource source = new ByteArrayDataSource("file name", "contentType", inlineFileObjectCreated.getBytes() ); JavaMailSender mailSender = (JavaMailSender) ServicesHome.getService("javaMailSender"); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(toArray); mimeMessageHelper.setSubject(""); mimeMessageHelper.setText(""); mimeMessageHelper.addAttachment("filename", source); mailSender.send(mimeMessageHelper.getMimeMessage());