JAVA MAIL API

JavaMail Projects

JavaMail Project 1

To Sending Attachment Message Using JavaMail API
Previous Home Next

Sending Attachment is like as forward messages. In your message text you add other part where the DataHandler for each is your attachment, It is a case of forwarded message. When you are read the attachment from a file. then your attachment Data Source for a filedataSorce. If you attachment any file for your messages then then reading from a URLDataSource. Once you have a DataSource, After pass on the DataHandler constructor.

Before attachment file in your Message or mail it to BodyPart with setDataHandler (). you Assuming the original filename for the attachment the last thing to do is to set the filename associated with the attachment with the setFileName()method of BodyPart.

package R4R;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendAttachFile 
{
    public static void main(String[] args) 
    {
  if (args.length != 5) 
  {
      System.out.println("usage: java sendfile <to> <from> <smtp> <file>");
      System.exit(1);
  }
  String to = args[0];
  String from = args[1];
  String host = args[2];
  String filename = args[3];
  String msgText1 = "Sending a file.\n";
  String subject = "Sending a file";
    // create some properties and get the default Session
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
    Session session = Session.getInstance(props, null);
  try 
  {

 

// create a message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgText1); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(filename); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mbp1); multipart.addBodyPart(mbp2); // add the Multipart to the message message.setContent(multipart); // set the Date: header message.setSentDate(new Date()); // send the message Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } } } }
Previous Home Next