[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Formmail in JSP

Posted on 2003-11-17
4
Medium Priority
?
272 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 53

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 53

Accepted Solution

by:
Ryan Chong earned 500 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Originally, this post was published on Monitis Blog, you can check it here . It goes without saying that technology has transformed society and the very nature of how we live, work, and communicate in ways that would’ve been incomprehensible 5 ye…
CTAs encourage people to do something specific to show interest in your company, product or service. Keep reading to learn why CTAs should always be thought of as extremely important, albeit small, sections of websites.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

650 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