使用MultipartFile通过多个附件发送电子邮件

时间:2018-04-19 09:32:16

标签: java spring javamail

我正在使用MultipartFile发送包含多个附件的电子邮件。我的代码工作正常但我将每个文件存储在我的项目中然后我附加。我不想将该文件存储在任何地方,而是希望将文件直接发送给收件人。 我的代码是,

控制器:

@RequestMapping(value="/sendEmailAttachment",method=RequestMethod.POST)
public @ResponseBody Response sendEmail(@RequestParam("file") MultipartFile[] file,@ModelAttribute Email email) {
    SendEmail mail = new SendEmail();
    return mail.sendEmail(email,file);
}

服务:

public Response sendEmail(Email email,MultipartFile[] attachFiles) {
username = email.getUsername();
password = email.getPassword();
switch (email.getDomain()) {
case "1and1.com":
    host = "smtp.1and1.com";
    break;
case "gmail.com":
    host = "smtp.gmail.com";
    break;
case "yahoo.com":
    host = "smtp.mail.yahoo.com";
    break;
case "rediffmail.com":
    host = "smtp.rediffmail.com";
    break;
default:
    host = "smtp.1and1.com";
    username="support@gmail.com";
    password="************";
    break;
}
props.put("mail.smtp.host", host);
    Response response = new Response();

         Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                  });
         try {
             // Create a default MimeMessage object.
             Message message = new MimeMessage(session);
             InternetAddress[] myToList = InternetAddress.parse(email.getTo());
                InternetAddress[] myBccList = InternetAddress.parse(email.getBcc());
                InternetAddress[] myCcList = InternetAddress.parse(email.getCc());
             // Set From: header field of the header.
             message.setFrom(new InternetAddress(email.getUsername()));

             // Set To: header field of the header.
             message.setRecipients(Message.RecipientType.TO,myToList);
                message.setRecipients(Message.RecipientType.BCC, myBccList);
                message.setRecipients(Message.RecipientType.CC, myCcList);

             // Set Subject: header field
             message.setSubject(email.getSubject());

             // Create the message part
             BodyPart messageBodyPart = new MimeBodyPart();

             // Now set the actual message
             messageBodyPart.setContent(email.getBody(), "text/html");

             // Create a multipar message
             Multipart multipart = new MimeMultipart();

             // Set text message part
             multipart.addBodyPart(messageBodyPart);

             if(attachFiles != null && attachFiles.length > 0){
                    for (MultipartFile filePath : attachFiles) {
                        MimeBodyPart attachPart = new MimeBodyPart();
                        try {
                            filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
                            attachPart.attachFile(filePath.getOriginalFilename());
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        multipart.addBodyPart(attachPart);
                    }
                }

             // Send the complete message parts
             message.setContent(multipart);
        //    Transport.send(message, message.getAllRecipients());
             Transport.send(message);

             response.setStatus(200);
             response.setMessage("Sent Email Successfully");

          } catch (MessagingException e) {
              response.setStatus(-1);
                response.setMessage(""+e);
                response.setObject(e);
                e.printStackTrace();
          }


        return response;

}

我在这里很喜欢,

filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
                        attachPart.attachFile(filePath.getOriginalFilename()); 

我不想将文件传输/保存到项目中并附加,我想直接发送文件。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

试试这个:

attachPart.setContent(filePath.getBytes(), filePath.getContentType());
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);

答案 1 :(得分:0)

在我的情况下,@ Bill Shannon的回答给我错误^[[2K

我修改了这样的代码:

"java.io.IOException: “text/plain” DataContentHandler requires String object, was given object of type class [B"

答案 2 :(得分:0)

如果您使用的是 Spring,那么您可以使用 JavaMailSenderImplMimeMessageHelper

JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
helper.addAttachment("fileName", filePath);
mailSender.send(mailMessage);