Solved

Formmail in JSP

Posted on 2003-11-17
4
266 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 51

Expert Comment

by:Ryan Chong
ID: 9763162
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 51

Accepted Solution

by:
Ryan Chong earned 125 total points
ID: 9763182
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Best environment for cross platform web development? 5 69
what are list of ebay api errors 1 34
xss alert in domino url 9 51
Web Easy Professional 10 Embedded Facebook 1 37
Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
This video teaches users how to migrate an existing Wordpress website to a new domain.
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

685 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