2017-07-06 67 views
-3

標題說明了所有內容: 如何將pdf文件提交給來自Java應用程序的通用電子郵件?如何通過來自Java的電子郵件發送pdf

+1

請編輯您的問題,除去PDFBox的所有提及。你的問題基本上是如何通過使用java的smtp發送文件。 –

回答

1

可以使用這個參考用PDF文件發送電子郵件作爲附件 -

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

class SendMailWithAttachment 
{ 
    public static void main(String [] args) 
    {  
     String to="[email protected]"; //Email address of the recipient 
     final String user="[email protected]"; //Email address of sender 
     final String password="xxxxx"; //Password of the sender's email 

     //Get the session object  
     Properties properties = System.getProperties(); 

     //Here pass your smtp server url 
     properties.setProperty("mail.smtp.host", "mail.javatpoint.com"); 
     properties.put("mail.smtp.auth", "true");  

     Session session = Session.getDefaultInstance(properties, 
       new javax.mail.Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(user,password); } });  

     //Compose message  
     try{  
      MimeMessage message = new MimeMessage(session);  
      message.setFrom(new InternetAddress(user));  
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
      message.setSubject("Message Aleart");   

      //Create MimeBodyPart object and set your message text   
      BodyPart messageBodyPart1 = new MimeBodyPart();  
      messageBodyPart1.setText("This is message body");   

      //Create new MimeBodyPart object and set DataHandler object to this object   
      MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
      String filename = "YourPDFFileName.pdf";//change accordingly  
      DataSource source = new FileDataSource(filename);  
      messageBodyPart2.setDataHandler(new DataHandler(source));  
      messageBodyPart2.setFileName(filename);    

      //Create Multipart object and add MimeBodyPart objects to this object   
      Multipart multipart = new MimeMultipart();  
      multipart.addBodyPart(messageBodyPart1);  
      multipart.addBodyPart(messageBodyPart2);  

      //Set the multiplart object to the message object  
      message.setContent(multipart);   

      //Send message  
      Transport.send(message);  
      System.out.println("message sent...."); 

     }catch (MessagingException ex) {ex.printStackTrace();} 
    } 
} 

您也可以參考JavaTPoint

+0

謝謝。但我收到此錯誤: com.sun.mail.smtp.SMTPSendFailedException:550訪問被拒絕 - 無效HELO域名(參見RFC2821 4.1.1.1) \t在com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport。的java:1829) \t在com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368) \t在com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886) \t在的javax .mail.Transport.send0(Transport.java:191) \t在javax.mail.Transport.send(Transport.java:120) \t在testemail.SendMailWithAttachment.main(SendMailWithAttachment.java:53) –

+0

@Da尼爾桑我認爲你只是複製上面的代碼。我在回答中添加了評論,請檢查一下。 –

相關問題