• Register

For distribution of  email with additional file of any type, JavaMail API delivers roughly valuable classes like BodyPart, MimeBodyPart.

For improved thoughtful of this instance, learn the stages of transfer email using JavaMail API first.

There are total sevem stages for sending attachment with email. They are:Distribution email with additional file using JavaMail API

  1. Catch the session object
  2. type message
  3. generate MimeBodyPart1 object and set your message text
  4. generate new MimeBodyPart1 obj and set DataHandler obj to this obj
  5. generate Multipart obj and add MimeBodyPart1 obj to this obj
  6. set the multiplart obj to the message obj
  7. deliever message

Example of sending email with attachment in Java.

1.	class SendAttachment1{  
2.	 public static void main(String [] args){  
3.	  
4.	  String to1="mubashir1987@gmail.com"; 
5.	  final String user1="muddasir234@gmail.com";
6.	  final String password1="xxxxx";
7.	  Properties properties1 = System.getProperties();  
8.	  Properties1.setProperty("mail.smtp.host", "mail.javatpoint.com");  
9.	  Properties1.put("mail.smtp.auth", "true");  
10.	  
11.	  Session session1 = Session.getDefaultInstance(properties1,  
12.	   new javax.mail.Authenticator() {  
13.	   protected PasswordAuthentication getPasswordAuthentication() {  
14.	   return new PasswordAuthentication(user,password);  
15.	   }  
16.	  });  
17.	  try{  
18.	    MimeMessage message1 = new MimeMessage(session);  
19.	    Message1.setFrom(new InternetAddress(user));  
20.	    Message1.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
21.	    Message1.setSubject("Message Aleart");  
22.	    BodyPart messageBodyPart11 = new MimeBodyPart();  
23.	    messageBodyPart11.setText("This is message body");  
24.	    MimeBodyPart messageBodyPart21 = new MimeBodyPart();  
25.	    String filename1 = "SendAttachment.java";
26.	    DataSource source1 = new FileDataSource(filename1);  
27.	    messageBodyPart21.setDataHandler(new DataHandler(source1));  
28.	    messageBodyPart21.setFileName(filename1);  
29.	    Multipart multipart1 = new MimeMultipart();  
30.	    multipart.addBodyPart(messageBodyPart11);  
31.	    multipart.addBodyPart(messageBodyPart21);  
32.	    message.setContent(multipart);  
33.	    Transport.send(message1);  
34.	   System.out.println("message has been sent");  
35.	   }catch (MessagingException ex) {ex.printStackTrace();}  
36.	 }  
37.	}  

  

 

2,760 points
7 4