Solved

Formmail in JSP

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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
WordPress: Debugging from my Windows 10 Desktop 6 93
Show MP4 file and close (HTA) 3 42
PHP Web Development 6 67
website linking 3 22
Does your audience prefer people in photos or no people? How can you best highlight what you’re selling? What are your competitors doing, and what can you do that is different and unique from them?  Continue reading to learn how to make your images …
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?
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

734 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