2015-10-23 26 views
2

我想知道我在做什麼錯在這裏(我失蹤)。我的電子郵件確實發送出去,但沒有附件。我發送的文件簡單地稱爲「日誌」。正如你將看到我在這裏想多事情,我也嘗試過它們一個接一個,但他們都不工作:附加文件到電子郵件在java

  MimeMessage message = new MimeMessage(session); 
      MimeBodyPart emailAttachment = new MimeBodyPart(); 
      Multipart multipart = new MimeMultipart(); 
      int len = build.getLogFile().getPath().length(); 
      //I have verified that "file" provides the right path 
      String file = build.getLogFile().getPath().substring(0, (len-3)); 
      String fileName = "log"; 
      DataSource source = new FileDataSource(file); 
      emailAttachment.setDataHandler(new DataHandler(source)); 
      //I know this .attachFile is not needed but I added it when nothing was working 
      emailAttachment.attachFile(build.getLogFile()); 
      emailAttachment.setFileName(fileName); 
      multipart.addBodyPart(emailAttachment); 
      message.setContent(multipart); 
      message.setFrom(adminAddress); 
      message.setText(builder.toString()); 
      message.setSentDate(new Date()); 


      mailSender.send(message); 

感謝

+0

它可能有助於http://stackoverflow.com/questions/17156544/sending-an-email-with-an-attachment-using-javamail-api –

+0

你是否確定你引用的文件_exists_並且還有內容?除了這種可能性,你的代碼看起來很好。 –

+0

我認爲你應該嘗試調試並逐行通過你的發送方法。 –

回答

0

使用此代碼=>

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class SendFileEmail 
{ 
public static void main(String [] args) 
{ 


    String to = "[email protected]"; 

    String from = "[email protected]"; 

    String host = "localhost"; 

    Properties properties = System.getProperties(); 

    properties.setProperty("mail.smtp.host", host); 

    Session session = Session.getDefaultInstance(properties); 

    try{ 

    MimeMessage message = new MimeMessage(session); 

    message.setFrom(new InternetAddress(from)); 

    message.addRecipient(Message.RecipientType.TO, 
           new InternetAddress(to)); 

    message.setSubject("This is the Subject Line!"); 

    BodyPart messageBodyPart = new MimeBodyPart(); 

    messageBodyPart.setText("This is message body"); 

    Multipart multipart = new MimeMultipart(); 

    multipart.addBodyPart(messageBodyPart); 

    messageBodyPart = new MimeBodyPart(); 
    String filename = "file.txt"; 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 
    multipart.addBodyPart(messageBodyPart); 


    message.setContent(multipart); 


    Transport.send(message); 
    System.out.println("Sent message successfully...."); 
    }catch (MessagingException mex) { 
    mex.printStackTrace(); 
    } 
} 
} 
+0

沒有運氣,結果相同。感謝帖子雖然 –