Solved

Formmail in JSP

Posted on 2003-11-17
4
268 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 52

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 52

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

729 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