Wrox Home  
Search P2P Archive for: Go

  Return to Index  

servlets thread: servlet e-mail


Message #1 by "Zhenwei Dan" <zdan8@y...> on Sun, 3 Dec 2000 23:08:47 -0000
Hi,
U should use the JavaMail API for that.  Hope this piece of code helps.
Just use this code in ur servlet. The code is for a multi-part mail.

Cheers,
arun

String sendTo = "receiver's mail id";
    String sentFrom = "sender's mail id";
    String senderName = "sender's name";
    String msgSubject = "Test Msg for JavaMail";
    String mailHost = "mail server's name or IP";


    Properties props = System.getProperties();
    props.put("mail.smtp.host",mailHost);

    Session session = Session.getDefaultInstance(props,null);
    //Session.setDebug(false);

    try
    {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(sentFrom,senderName));
      InternetAddress[] address = {new InternetAddress(sendTo)};
      msg.setRecipients(Message.RecipientType.TO,address);
      msg.setSubject(msgSubject);
      msg.setSentDate(new Date());
      //msg.setText(msgSubject+"thats subject");

      // mutli part mailer with attachment
      MimeBodyPart mbp1 = new MimeBodyPart();
      //String matter = "<html><head><title></title></head><body><a
href=\"http://192.168.1.90:7001/dts/login.html\">Login to
DTS</a></body></html>";
      //String matter = "http://192.168.1.90:7001/dts/login.html";
      URL login = new URL("http://192.168.1.90:7001/dts/href.html");
      URLDataSource URLds = new URLDataSource(login);
      DataHandler dh = new DataHandler(URLds);
      mbp1.setDataHandler(dh);
      System.out.println("after setting url data source");

      /*
      mbp1.setDataHandler(new DataHandler(matter,"text/html"));
      mbp1.setText(matter);

      mbp1.setContent(matter,"text/html");
      mbp1.setContent(matter);
      mbp1.setText(msgSubject+"<a
href=\"http://192.168.1.90:7001/dts/login.html\">Login to DTS</a>");
      mbp1.setText(msgSubject+"\n
http://192.168.1.90:7001/dts/login.html");
      */

      MimeBodyPart mbp2 = new MimeBodyPart();
      FileDataSource fileAttachment = new
FileDataSource("addanemployee.html");
      //set data handler
      mbp2.setDataHandler(new DataHandler(fileAttachment));
      mbp2.setFileName("addanemployee.html");
      //create Mulipart
      Multipart mp = new MimeMultipart();
      //mp.contentType = "text/html";
      System.out.println("before adding multi part");
      mp.addBodyPart(mbp1);
      mp.addBodyPart(mbp2);

      // add mulipart content to message
      msg.setContent(mp);
      // send the message
      System.out.println("before sending");
      Transport.send(msg);
      System.out.println("after sending");
    }catch(MessagingException e)
     {
      e.printStackTrace();
      System.out.println("Error is Messaging");
      return;
     }
     catch(Exception ex)
     {
      ex.printStackTrace();
      return;
     }



  Return to Index