通过msg.setContent(multipart)向邮件添加附件会导致它不再被发送

时间:2015-08-18 11:16:48

标签: java javamail attachment

我有以下代码用于向目标用户发送电子邮件的servlet程序。它工作正常,直到程序中没有附件,但是当我将文件附加到它时,它没有向目的地发送任何电子邮件。  我在下面的程序中标记了---- msg.setContent(multipart),当我用multipart对象设置消息的内容时,它不会触发电子邮件,否则它对于仅包含内容的邮件工作正常。

我无法理解我在哪里做错了,虽然我已将mail.jar更新为mail_1.4.jar和mail_1.5 jar,并根据mail_1.4.jar中的更新使用了attachFile()方法。 / p>

String host = "asmtp.ccccs.com";
String to =  "abc@gmail.com";
String from =  "abc@gmail.com"; 
String subject ="hi";
String messageText ="yuppppp";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);

// Set debug on the Session
// Passing false will not echo debug info, and passing True will.

mailSession.setDebug(sessionDebug);

// Instantiate a new MimeMessage and fill it with the 
// required information.

Message msg = new MimeMessage(mailSession);
try{
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
response.setContentType("text/html");
     PrintWriter out = response.getWriter();


      BodyPart   messageBodyPart = new MimeBodyPart();

         // Fill the message
      //   messageBodyPart.setText("This is message body");
         messageBodyPart.setContent(msg, "text/html");


          MimeBodyPart messageBodyPart2 = new MimeBodyPart();  


         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         out.println("1");
         String filename = "C:/Users/Desktop/Conn.java";
         out.println("2");

         //String sigPath = context.getRealPath("/images/Discovery_email_sig.jpg");
         //  File sigFile = new File(sigPath);

         DataSource source = new FileDataSource(filename);
         out.println("3");out.println(source);
         messageBodyPart2.setDataHandler(new DataHandler(source));
         out.println("4");
         messageBodyPart2.setFileName(filename);
         out.println("5");

         messageBodyPart2.attachFile(filename);

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

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

         // Send the complete message parts
        msg.setContent(multipart);//// ----- When i am setting this, then email with attachment is not getting delievred

     out.println("7");
Transport.send(msg);
out.println("8");
out.println("Mail was sent to " + to);
out.println(" from " + from);
out.println(" using host " + host + ".");
}catch(Exception e){

out.println(e);
}

0 个答案:

没有答案