2014-06-17 79 views
0

爲什麼無法發送郵件和附件 當我在下面使用此代碼時,它將發送郵件和附件,但不會發送郵件。一些誰知道爲什麼或如何?發送帶附件的郵件和一條消息

工作代碼,我已經使用Java Mail 1.4.7 jar。

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

public class MailProjectClass { 

public static void main(String[] args) { 

    final String username = "[email protected]"; 
    final String password = "your.password"; 

    Properties props = new Properties(); 
    props.put("mail.smtp.auth", true); 
    props.put("mail.smtp.starttls.enable", true); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.port", "587"); 

    Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(username, password); 
       } 
      }); 

    try { 

     Message message = new MimeMessage(session); 
     message.setFrom(new InternetAddress("[email protected]")); 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse("[email protected]")); 
     message.setSubject("Testing Subject"); 
     message.setText("PFA"); 

     MimeBodyPart messageBodyPart = new MimeBodyPart(); 

     Multipart multipart = new MimeMultipart(); 

     messageBodyPart = new MimeBodyPart(); 
     String file = "path of file to be attached"; 
     String fileName = "attachmentName"; 
     DataSource source = new FileDataSource(file); 
     messageBodyPart.setDataHandler(new DataHandler(source)); 
     messageBodyPart.setFileName(fileName); 
     multipart.addBodyPart(messageBodyPart); 

     message.setContent(multipart); 

     System.out.println("Sending"); 

     Transport.send(message); 

     System.out.println("Done"); 

    } catch (MessagingException e) { 
     e.printStackTrace(); 
    } 
    } 
} 
+1

,能得到任何異常?如果是的話發佈。 –

+0

不,我沒有得到任何異常,它通常運行代碼 – Jeroen

回答

2

您需要添加電子郵件正文作爲單獨的多部分

String body="Email body template"; 
MimeBodyPart mailBody = new MimeBodyPart(); 
mailBody.setText(body); 
multipart.addBodyPart(mailBody); 
+0

謝謝,現在它適合我! – Jeroen

0

考慮,你錯過了;這裏String fileName = "attachmentName"爲錯字的事實。

但除此之外,你的代碼工作得很好。

+0

感謝您的更改它編輯文本,因爲個人信息,並忘記了; – Jeroen

+0

什麼是附件的文件格式和大小? – Adheep

+0

.TXT文件大小:363字節,但它可以更大,如果我要使用它 – Jeroen