2014-06-17 4 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 파일 크기 : 363bytes하지만 사용하면 더 커질 수 있습니다. – Jeroen

관련 문제