Solved

Formmail in JSP

Posted on 2003-11-17
4
260 Views
Last Modified: 2011-04-14
Is there anybody who can give me a tip on creating an e-mail form based on jsp? I`m not an JSP programmer.. I only have an ISP who who delivers this language as an dynamic option.. Please help me!
0
Comment
Question by:oppdal
  • 2
4 Comments
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
I got a send mail class that i usually use, do take a look:

libmail_wc.java:

package app;

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.text.SimpleDateFormat;

public class libmail_wc extends Thread {
    private String uname = ""; //Sender Name
    private String uemail = ""; //Sender Email
    private String rname = ""; //Refer Name
    private String remail = ""; //Refer Email
    private String smtp = "";
    private String rootpath = "";
    private String imgrootpath = "";
    private String contenttype = "text"; //text or file
    private String content = "";
    private String filepath = "content.htm";
    private String subject = "";
      private String para = "";

      private String msgLog = "";
    private String norefer = "";

    private String dirBase = "";
      private String dirWork = "";
      private String dirProc = "";
      private String dirLogs = "";
    private String dirBad = "";

    public libmail_wc(String uname, String uemail, String rname, String remail, String smtp, String subject, String rootpath, String imgrootpath, String logpath, String contenttype, String content, String filepath, String para) {
        this.uname = uname;
        this.uemail = uemail;
        this.rname = rname;
        this.remail = remail;
        this.smtp = smtp;
        this.rootpath = rootpath;
        this.imgrootpath = imgrootpath;
        this.contenttype = contenttype; //text or file
        this.content = content;
        this.filepath = filepath;
            this.subject = subject;
            this.para = para;

            this.dirBase = logpath;
            this.dirWork = this.dirBase + "/work";
            this.dirProc = this.dirBase + "/proc";
            this.dirLogs = this.dirBase + "/logs";
          this.dirBad = this.dirBase + "/bad";

   }


    public void run()  {

        msgLog = uemail;

      try{


            String txtContent = "";

            if (this.contenttype.equals("text")) {
                  txtContent = content;
            } else {

                  //Try open the file.
                  txtContent = getContent(filepath,rname,uname,rootpath,imgrootpath);

            }


            if (true) {
                  Properties props = new Properties();
                  props.put("mail.smtp.host", smtp);

                  Session session = Session.getDefaultInstance(props, null);
                  Message msg = new MimeMessage(session);

                  //Set Sender Info
                  InternetAddress sender = new InternetAddress(uemail);
                  if (!uname.equals("")) { sender.setPersonal(uname); }
                  msg.setFrom(sender);

                  //InternetAddress[] address1 = {new InternetAddress(remail)};
                  //msg.setRecipients(Message.RecipientType.TO, address1);

                  //Set Receiver Info
                  InternetAddress[] receiver = {new InternetAddress(remail)};
                  if (!rname.equals("")) { receiver[0].setPersonal(rname); }
                  msg.setRecipients(Message.RecipientType.TO, receiver);

                  msg.setSubject(subject);
                  msg.setSentDate(new Date());

                  msg.setContent(txtContent, "text/html");

                  Transport.send(msg);


             msgLog += " - sendmail_success -";
          }else{
             msgLog += " - not_sent_becuz_file_error -";
          }
      } catch (IOException ioex) {
          msgLog += " [ERROR] I/O: " + ioex.getMessage();
      } catch (MessagingException mex) {
          msgLog += " [ERROR] MAIL: " + mex.getMessage();

          mex.printStackTrace();
          Exception ex = mex;
          do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException)ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                      msgLog += " *Invalid Addresses";
                  if (invalid != null) {
                      for (int i = 0; i < invalid.length; i++)
                            msgLog += "  " + invalid[i];
                  }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                      msgLog += " *ValidUnsent Addresses";
                  if (validUnsent != null) {
                      for (int i = 0; i < validUnsent.length; i++)
                            msgLog += "  " + validUnsent[i];
                  }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                      msgLog += " *Validsent Addresses";
                  if (validSent != null) {
                      for (int i = 0; i < validSent.length; i++)
                            msgLog += "  " + validSent[i];
                  }
                }
            }
          } while ((ex = ((MessagingException)ex).getNextException())
                 != null);
      } catch (Exception e) {
          msgLog += " [ERROR] GENERAL: " + e.getMessage();
      }finally{
          makeLog();
      }
    }


    public String getContent(String contentfile,String receiver, String sender, String rootpath, String imgrootpath) throws IOException {
            if (contentfile.equals("")) return content;
            try {

                  File f = new File(contentfile);

                  StringBuffer strmsg = new StringBuffer();
                  String s = "";

                  if (f.exists()) {
                        BufferedReader d  = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(f))));
                        while((s = d.readLine())!= null) {
                              strmsg.append(s+"\n");
                        }
                        d.close();

                        String out = strmsg.toString();

                        out = searchReplace(out,"<%=Receiver%>",receiver);
                        out = searchReplace(out,"<%=Sender%>",sender);
                        out = searchReplace(out,"<%=RootPath%>",rootpath);
                        out = searchReplace(out,"<%=ImgRootPath%>",imgrootpath);

                        System.out.println("para mail = "+para);

                        if (!para.equals("")) {
                              String tmp = para;
                              String arr[] = tmp.split("\\|\\|\\|");

                              for (int i=0;i<arr.length;i++) {
                                    String arr2[] = arr[i].split("\\=\\=");

                                    if (arr2.length == 2) {
                                          out = searchReplace(out,arr2[0], arr2[1]);
                                    }
                              }
                        }



                        return out;
                  } else {
                        return content;
                  }
            } catch(Exception e) {
                  System.out.println("Cannot read file ("+ contentfile +"): " +e);
                  return content;
            }
      }


      public void makeLog()  {
            try{
              Date today;

              TimeZone tz = TimeZone.getTimeZone("CTT");
              tz.setDefault(tz);

              today = new Date();
              SimpleDateFormat formatter1 =
                                          new SimpleDateFormat("ddMMMyyyy H:mm:ss");
              String currtime = formatter1.format(today);

              SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd");
              String logname = formatter2.format(today);

              FileWriter fw = new FileWriter(dirLogs + "/" +logname + ".txt", true);
              fw.write(currtime + " - " + msgLog + "\r\n");
              fw.flush();
              fw.close();
            } catch (IOException e) {
                  System.out.println("i/o error from makeLog!");
            }
      }


      public static String searchReplace(String inString, String find, String replace)
      {

            if (inString==null || find == null || replace == null) {
                  return inString;
            }

            if(inString.length() == 0) {
                  return inString;
            }

            int i = inString.indexOf(find);
            if (i == -1) {
                  return inString;
            } else {
                  return inString.substring(0,i) + replace +
                  searchReplace(inString.substring(i + find.length()), find, replace);
            }
      }

}

Hope this helps
0
 
LVL 49

Accepted Solution

by:
Ryan Chong earned 125 total points
Comment Utility
To use it, try like:

<%@page import="app.*"%>

<%

String SMTP = "smtp.domain.com";
      
      String imgRootPath = ""; //Reserved
      String RootPath = ""; //Reserved
      
      String adminSenderName = "<Sender>";
      String adminSenderEmail = "admin@domain.net";
      

String referfirstname = (request.getParameter("referfirstname")==null)?"":request.getParameter("referfirstname");
      String refersurname = (request.getParameter("refersurname")==null)?"":request.getParameter("refersurname");
      String referemail = (request.getParameter("referemail")==null)?"":request.getParameter("referemail");
      
      String friendfirstname1 = (request.getParameter("friendfirstname1")==null)?"":request.getParameter("friendfirstname1");
      String friendsurname1 = (request.getParameter("friendsurname1")==null)?"":request.getParameter("friendsurname1");
      String friendemail1 = (request.getParameter("friendemail1")==null)?"":request.getParameter("friendemail1");
      
if (!friendsurname1.equals("") && !friendemail1.equals("")) {
                  
                  try {
                        libmail_wc mail = new libmail_wc(adminSenderName, adminSenderEmail, friendfirstname1 +  " " + friendsurname1, friendemail1, SMTP, "<Subject to change>", RootPath, imgRootPath, l, "file", "No Value", localedmpath, para);
                        mail.start();                        
                  } catch (Exception e) {}
                  System.out.println("Sent 1");                        
            }      

%>
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Search console 3 59
tweaks to widgets on home page 17 36
Which is the latest version of Apache Tomcatl 3 35
Select2 jquery help 9 41
Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now