2014-03-06 47 views
0

我有問題,就是當我打電話multipart.addBodyPart(msgbodypart);它說,我應該在BodyPart msgbodypart = new MimeBodyPart();改變msgbodypart類型MimeBodyPartmsgbodypart = new MimeBodyPart();Java郵件發送者無法正常工作

好吧,我改變它,那麼它滴警告:

在類型多部分的方法addBodyPart(BodyPart的)不適用於參數(MimeBodyPart的)

現在怎麼辦?

try { 
    MimeMessage msg = new MimeMessage(session); 
    msg.setFrom(new InternetAddress(username)); 
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
    msg.setSubject("Test Java Sending Zip File"); 
    msg.setText("This is a message from a java program"); 

    BodyPart msgbodypart = new MimeBodyPart(); 

    msgbodypart.setText("this is msg Body"); 

    Multipart multipart = new MimeMultipart(); 

    msgbodypart = new MimeBodyPart(); 

    String filename = "zips.txt"; 

    DataSource source = new FileDataSource(filename); 
    msgbodypart.setDataHandler(new DataHandler(source)); 
    msg.setFileName(filename); 
    multipart.addBodyPart(msgbodypart); 
    msg.setContent(multipart); 

    System.out.println("Sending"); 
    Transport.send(msg); 
    System.out.println("Sent!"); 
} catch (MessagingException mex) { 
    mex.printStackTrace(); 
} 
+0

您可能需要檢查您的導入。確保它們全部來自'javax.mail ...'包。 –

回答

0

使用舊的lib。 JavaMail API 1.4有此選項

+0

你的問題解決了嗎? :) –

+0

是的,我很抱歉 – chabeee

0
final Session connection = Session.getInstance(props, null); 
final Message message = new MimeMessage(connection); 
final BodyPart bodyPart1 = new MimeBodyPart(); 
final BodyPart bodyPart2 = new MimeBodyPart(); 
final Multipart multiPart = new MimeMultipart(); 
connection.setDebug(true); 
try { 
    final Address toAddress = new InternetAddress(
    "RECEIVER-EMAIL-ADDRESS"); 
    final Address fromAddress = new InternetAddress(senderUserName); 
    final String content = "Please check your attachments for a zip file"; 

    message.setSubject("Test Java Sending Zip File"); 

    bodyPart1.setText(content); 
    DataSource dataSource = new FileDataSource("D:\\Data.zip"); 
    bodyPart2.setDataHandler(new DataHandler(dataSource)); 
    bodyPart2.setFileName(dataSource.getName()); 

    multiPart.addBodyPart(bodyPart1); 
    multiPart.addBodyPart(bodyPart2); 
    message.setContent(multiPart); 

    message.setFrom(fromAddress); 
    message.setRecipient(javax.mail.Message.RecipientType.TO, toAddress); 
    Transport transport = connection.getTransport("smtp"); 
    transport.connect(smtpServer, senderUserName, senderPassword); 
    transport.sendMessage(message, message.getAllRecipients()); 
    System.out.println("DONE !"); 
} catch (AddressException e) { 
    e.printStackTrace(); 
    throw new Exception(e); 
} 
相關問題