如何通过Java发送电子邮件发送pdf

时间:2017-07-06 09:53:33

标签: java email email-attachments

标题说明了一切: 如何将pdf文件从Java应用程序提交到通用电子邮件?

1 个答案:

答案 0 :(得分: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="XYZ@abc.com"; //Email address of the recipient
        final String user="ABC@XYZ.com"; //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

相关问题