Sending Email using java code

I am using the following code to send an email from my java servlet but the problem is, when it is on its own it works fine but as soon as I combine it with some code to submit data into a postgres database it sometimes does not perform could it be because im missing some close statements??
//grades to submit grades starts here
                                                       String [] paramValues = req.getParameterValues("Mark");
                                                  for(int i=0; i<paramValues.length;i++)
                                                       String [] paramValues2 = req.getParameterValues("StudentExamNumber");
                                                            String Mark = paramValues;
                                                            String ExamNo = paramValues2[i];
                                                            //testing purposes
                                                            out.println("<tr><td>"+ExamNo+"</td>");
                                                            out.println("<td>"+Mark+"</td>");
                                                            try
                                                       st = conn.createStatement();
                                                       query = "SELECT StudentNo FROM STUDENTS"+WebCourse2+ " where ExamNo='"+ExamNo+"'";
                                                       rs = st.executeQuery(query);
                                                       if(rs !=null)
                                                                      while(rs.next())
                                                                           String StudentNo=rs.getString("StudentNo");
                                                                           //testing purposes
                                                                           //out.println("<td>"+StudentNo+"</td></tr>");
                                                                           here
                                                                           st4 = conn.createStatement();
                                                                 query4 = "select MAX(entryno) from STUDENTRESULTSFORCOURSE"+WebCourse2+" WHERE STUDENTNO='"+StudentNo+"'";
                                                                 rs4 = st4.executeQuery(query4);
                                                                 if(rs4 !=null)
                                                                                while(rs4.next())
                                                                                     EntryNo = rs4.getInt(1);
                                                                                }//end rs4 while
                                                                                rs4.close();
                                                                           }//end rs4 if
                                                                 out.println("<tr><td>EntryNo= "+EntryNo+"</td>");
                                                                           EntryNo = EntryNo + 1;
                                                                           out.println("<td>NewEntryNo= "+EntryNo+"</td></tr>");
                                                                           //Submitting grades to database/
                                                                 st3 = conn.createStatement();
                                                                 insert = "insert into STUDENTRESULTSFORCOURSE"+WebCourse2+" (StudentNo, CourseCode, AttemptNo, ExamMark, EntryNo, EnteredBy) values ('"+StudentNo+"', '"+WebCourse2+"', 1,'"+Mark+"',"+EntryNo+",'"+WebUsername2+"')";
                                                                 st3.executeUpdate(insert);
                                                                      }//end rs while
                                                                      rs.close();
                                                                 }//end rs if
                                                            }//end try
                                                            catch (SQLException e)
                                                                 System.out.println("Error: "+e.getMessage());
                                                       }//end for loop     
                                                       //code to submit grades ends here
                                                       //code used to send email starts here
                                                       String m_sHostName="localhost";
                                                  int m_iPort=25;
                                                       try
                                                            // Open port to server
                                                            smtpSocket = new Socket(m_sHostName, m_iPort);
                                                            os = new DataOutputStream(smtpSocket.getOutputStream());
                                                            is = new DataInputStream(smtpSocket.getInputStream());
                                                            if(smtpSocket != null && os != null && is != null)
                                                                 // Connection was made. Socket is ready for use.
                                                                 System.out.println("Connection was made. Socket is ready for use.");
                                                                 try
                                                                      // The email address that the server
                                                                      // you are using know user as.
                                                                      os.writeBytes("MAIL From: <[email protected]>\r\n");
                                                                      // Who the email is going to.
                                                                      os.writeBytes("RCPT To: <[email protected]>\r\n");
                                                                      //send a CC to:
                                                                      os.writeBytes("RCPT Cc: <[email protected]>\r\n");
                                                                      // add the message and the
                                                                      // header of the email to be sent out.
                                                                      os.writeBytes("DATA\r\n");
                                                                      os.writeBytes("X-Mailer: Via Java\r\n");
                                                                      os.writeBytes("From: "+WebUsername2+"<[email protected]>\r\n");
                                                                      os.writeBytes("To: Marie <[email protected]>\r\n");
                                                                      //Again if you want to send a CC then add this.
                                                                      os.writeBytes("Cc: ProfCuthbert <[email protected]>\r\n");
                                                                      String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
                                                                      os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
                                                                      os.writeBytes(sMessage + "\r\n");
                                                                      os.writeBytes("\r\n.\r\n");
                                                                      os.writeBytes("QUIT\r\n");
                                                                      // Now send the email off and check the server reply.
                                                                      // Once an OK is reached you are complete.
                                                                      String responseline;
                                                                      //for testing purposes
                                                                      //out.println(responseline = is.readLine());
                                                                      while((responseline = is.readLine())!=null)
                                                                      //for testing purposes
                                                                      //out.println("responseline= "+responseline+"<br>");
                                                                      //out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
                                                                      if(responseline.indexOf("Ok") != -1)
                                                                      break;
                                                                      if(responseline.indexOf("Ok") == -1)
                                                                      confirm=1;
                                                                      if (confirm==1)
                                                                      out.println("<br>the marks have been submitted thank you");
                                                                      catch(Exception e)
                                                                      {  System.out.println("Cannot send email as an error occurred.");
                                                                           out.println("Cannot send email as an error occurred.");
                                                       catch(Exception e)
                                                       { System.out.println("Host " + m_sHostName + "unknown"); }
Does anyone know what the problem is??
thanks
tzaf

i close them later in the program. Ive made sure they are all closed I have a feeling that it could be coming from here....
//code used to send email starts here
                                                       String m_sHostName="localhost";
                                                  int m_iPort=25;
                                                       try
                                                            // Open port to server
                                                            smtpSocket = new Socket(m_sHostName, m_iPort);
                                                            os = new DataOutputStream(smtpSocket.getOutputStream());
                                                            is = new DataInputStream(smtpSocket.getInputStream());
                                                            if(smtpSocket != null && os != null && is != null)
                                                                 // Connection was made. Socket is ready for use.
                                                                 System.out.println("Connection was made. Socket is ready for use.");
                                                                 try
                                                                      // The email address that the server
                                                                      // you are using know user as.
                                                                      os.writeBytes("MAIL From: <email address>\r\n");
                                                                      // Who the email is going to.
                                                                      os.writeBytes("RCPT To: <email address>\r\n");
                                                                      //send a CC to:
                                                                      os.writeBytes("RCPT Cc: <email address>\r\n");
                                                                      // add the message and the
                                                                      // header of the email to be sent out.
                                                                      os.writeBytes("DATA\r\n");
                                                                      os.writeBytes("X-Mailer: Via Java\r\n");
                                                                      os.writeBytes("From: "+WebUsername2+"<email address>\r\n");
                                                                      os.writeBytes("To: hello<email address>\r\n");
                                                                      //Again if you want to send a CC then add this.
                                                                      os.writeBytes("Cc: hello <email address>\r\n");
                                                                      String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
                                                                      os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
                                                                      os.writeBytes(sMessage + "\r\n");
                                                                      os.writeBytes("\r\n.\r\n");
                                                                      os.writeBytes("QUIT\r\n");
                                                                      // Now send the email off and check the server reply.
                                                                      // Once an OK is reached you are complete.
                                                                      String responseline;
                                                                      //for testing purposes
                                                                      //out.println(responseline = is.readLine());
                                                                      while((responseline = is.readLine())!=null)
                                                                      //for testing purposes
                                                                      //out.println("responseline= "+responseline+"<br>");
                                                                      //out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
                                                                      if(responseline.indexOf("Ok") != -1)
                                                                      break;
                                                                      if(responseline.indexOf("Ok") == -1)
                                                                      confirm=1;
                                                                      if (confirm==1)
                                                                      out.println("<br>the marks have been submitted thank you");
                                                                      catch(Exception e)
                                                                      {  System.out.println("Cannot send email as an error occurred.");
                                                                           out.println("Cannot send email as an error occurred.");
                                                       catch(Exception e)
                                                       { System.out.println("Host " + m_sHostName + "unknown"); }
                                                       //code used to send email ends here
do i need to close is and os?
thanks
tzaf

Similar Messages

  • How to send emails using java code

    Hi,
    can any give me some sample code for sending emails using java language

    JavaMail quick start
    jGuru: Fundamentals of the JavaMail API

  • Sending email using java

    Im using this code to do this, but i have a feeling that I need to close os and is is that the case? do i need to close anything else?
    thanks
    tzaf
    //code used to send email starts here
                                                           String m_sHostName="localhost";
                                                      int m_iPort=25;
                                                           try
                                                                // Open port to server
                                                                smtpSocket = new Socket(m_sHostName, m_iPort);
                                                                os = new DataOutputStream(smtpSocket.getOutputStream());
                                                                is = new DataInputStream(smtpSocket.getInputStream());
                                                                if(smtpSocket != null && os != null && is != null)
                                                                     // Connection was made. Socket is ready for use.
                                                                     System.out.println("Connection was made. Socket is ready for use.");
                                                                     try
                                                                          // The email address that the server
                                                                          // you are using know user as.
                                                                          os.writeBytes("MAIL From: <[email protected]>\r\n");
                                                                          // Who the email is going to.
                                                                          os.writeBytes("RCPT To: <[email protected]>\r\n");
                                                                          //send a CC to:
                                                                          os.writeBytes("RCPT Cc: <[email protected]>\r\n");
                                                                          // add the message and the
                                                                          // header of the email to be sent out.
                                                                          os.writeBytes("DATA\r\n");
                                                                          os.writeBytes("X-Mailer: Via Java\r\n");
                                                                          os.writeBytes("From: "+WebUsername2+"<[email protected]>\r\n");
                                                                          os.writeBytes("To: Marie <[email protected]>\r\n");
                                                                          //Again if you want to send a CC then add this.
                                                                          os.writeBytes("Cc: ProfCuthbert <[email protected]>\r\n");
                                                                          String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
                                                                          os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
                                                                          os.writeBytes(sMessage + "\r\n");
                                                                          os.writeBytes("\r\n.\r\n");
                                                                          os.writeBytes("QUIT\r\n");
                                                                          // Now send the email off and check the server reply.
                                                                          // Once an OK is reached you are complete.
                                                                          String responseline;
                                                                          //for testing purposes
                                                                          //out.println(responseline = is.readLine());
                                                                          while((responseline = is.readLine())!=null)
                                                                          //for testing purposes
                                                                          //out.println("responseline= "+responseline+"<br>");
                                                                          //out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
                                                                          if(responseline.indexOf("Ok") != -1)
                                                                          break;
                                                                          if(responseline.indexOf("Ok") == -1)
                                                                          confirm=1;
                                                                          if (confirm==1)
                                                                          out.println("<br>the marks have been submitted thank you");
                                                                          catch(Exception e)
                                                                          {  System.out.println("Cannot send email as an error occurred.");
                                                                               out.println("Cannot send email as an error occurred.");
                                                           catch(Exception e)
                                                           { System.out.println("Host " + m_sHostName + "unknown"); }
                                                           //code used to send email ends here

    any thoughts?
    thanks
    tzaf

  • Can I send email using Java from my localhost(Tomcat) with Internet connect

    Hi friends,
    Please tell me can I send email from my localhost (Tomcat) using Java when my computer is connected to Internet?
    I don't have any SMTP username or password or the like, as I found in some codes available in net.
    Please suggest and any simple code if possible.
    Please don't send me the link of JavaMail API to read.
    ---Sujoy

    Thank you for the link. Though I have not tested the provided code, I will test it.
    --Sujoy                                                                                                                                                                                       

  • Error while sending Email through Java Code in OIM

    Hi All,
    I have created a java code using tcEmailNotificationUtil, and integrated the same with the adapter.
    I am triggering this adapter when an approval process gets completed.
    As soon as the approval process gets completed my email task is triggering but the task is getting rejected.
    I have checked my system configuration for mail server settings.Everything seems working fine.
    Can you please help me in this issue how to debug?
    Thanks in advance.

    Hi,
    Here is my log file:
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/insertTaskHistory left.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/run entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: ReIssueAuditMessage/execute entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: ReIssueAuditMessage/initialize entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/getAttribute entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/getAttribute left.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/getUtility entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/getUtility left.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.ACCOUNTMANAGEMENT] - Class/Method: tcUtilityFactory/getRemoteUtility - Data: moUtil - Value: Thor.API.Operations.tcAuditOperationsClient
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: ReIssueAuditMessage/initialize left.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: ReIssueAuditMessage/processAllByIdentifier entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped entered.
    DEBUG,25 Apr 2011 10:40:00,099,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped left.
    DEBUG,25 Apr 2011 10:40:00,100,[XELLERATE.DATABASE] - select A.* from (select aud_jms_key, aud_class, identifier from aud_jms order by aud_jms_key) A where rownum <= ?
    INFO,25 Apr 2011 10:40:00,101,[XELLERATE.PERFORMANCE] - Query: DB: 1, LOAD: 0, TOTAL: 1
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped entered.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped entered.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isStopped left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: ReIssueAuditMessage/execute left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/run left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isSuccess entered.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SCHEDULER.TASK] - Class/Method: SchedulerBaseTask/isSuccess left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SERVER] - Class/Method: SchedulerTaskLocater /removeLocalTask entered.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SERVER] - Class/Method: SchedulerTaskLocater /removeLocalTask left.
    DEBUG,25 Apr 2011 10:40:00,102,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/updateStatusToInactive entered.
    DEBUG,25 Apr 2011 10:40:00,104,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/updateStatusToInactive left.
    DEBUG,25 Apr 2011 10:40:00,104,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/updateTaskHistory entered.
    DEBUG,25 Apr 2011 10:40:00,106,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/updateTaskHistory left.
    DEBUG,25 Apr 2011 10:40:00,106,[XELLERATE.SERVER] - Clearing Security Associations with thread executing Scheduled task
    DEBUG,25 Apr 2011 10:40:00,106,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/run left.
    DEBUG,25 Apr 2011 10:40:00,106,[XELLERATE.SERVER] - Class/Method: QuartzWrapper/execute left.
    and I just wanted to ensure that my coding part is also fine.
    Posting the code even:
    tcDataProvider ioDatabase = new tcDataBaseClient();
    tcEmailNotificationUtil sendMail = new tcEmailNotificationUtil(ioDatabase);
    sendMail.setBody("Sample Message");
    sendMail.setSubject("subject");
    sendMail.setFromAddress("fromemailaddress");
    sendMail.sendEmail("recepient");
    Thanks in Advance.

  • I am not able to send email using JAVA API to outer email

    If I am trying to send email from my company account to yahoo I am getting following errors:
    javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
    for [email protected]
    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at MailSend.main(MailSend.java:116)
    Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to rel
    ay for [email protected]
    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
    ... 4 more
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for mkba
    [email protected]
    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at MailSend.main(MailSend.java:116)
    Please let me know the reason for the same.

    Unable to relay - This happened because your Company network don't permit relay. Do talk to the network administrator and check with way safe you can send.
    I got the same problem, now im using through gmail.

  • Send Email using Java

    May i know how to send the email by using java?

    heres my final i did for java 1 last year (it was a simple email sending program:
    //java FINAL!
    import javax.swing.*;
    import java.net.URL;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EmailProg extends JPanel implements ActionListener {
        protected JTextArea textArea;
        protected String newline = "\n";
        static final private String composemail = "compose";
        static final private String sendmail = "send";
        static final private String about = "about";
        static final private String submit = "submit";
        static final private String exit = "exit";
        JLabel lSubmit = new JLabel("Submit");
        JButton subbutton = new JButton();
        JTextArea emailfrom = new JTextArea(1,1);
        JTextArea emailto = new JTextArea(1, 1);
        JTextArea emailsubject = new JTextArea(1, 1);
        JTextArea emailmessage = new JTextArea(25, 1);
        //------BAG LAYOUT
        JLabel lFrom = new JLabel("From:");
        JTextField cFrom = new JTextField(32);
        JLabel lTo = new JLabel("To:");
        JTextField cTo = new JTextField(32);
        JFrame frame2 = new JFrame("Compose New");
        JLabel lSubject = new JLabel("Subject");
        JTextField cSubject = new JTextField(32);
        JLabel lMessage = new JLabel("Body");
        JTextArea cMessage = new JTextArea(5,32);
        //====================================
        public EmailProg() {
            super(new BorderLayout());
            //Create the toolbar.
            JToolBar toolBar = new JToolBar();
            addButtons(toolBar);
            //Create the text area used for output.  Request
            //enough space for 5 rows and 30 columns.
            textArea = new JTextArea(5, 30);
            textArea.setEditable(false);
            textArea.setText("Welcome to Jeff's email program! With this program you can compose and send emails. I hope I get a good grade on thise, and marine world finds a good use for it :-D:-D (implements really just testing the scroller!!!)");
            JScrollPane scrollPane = new JScrollPane(textArea);
            //Lay out the main panel.
            setPreferredSize(new Dimension(450, 110));
            add(toolBar, BorderLayout.NORTH);
            add(scrollPane, BorderLayout.CENTER);
        //==================================
        protected void addButtons(JToolBar toolBar) {
            JButton button = null;
            //first button
            button = makeNavigationButton("/toolbarButtonGraphics/general/ComposeMail24.gif", composemail ,"Compose new Email", "compose new");
            toolBar.add(button);
            //second button
            button = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", sendmail,"Send The Mail","send");
            toolBar.add(button);
            //third button
            button = makeNavigationButton("toolbarButtonGraphics/general/About24.gif", about,"About","About");
            toolBar.add(button);
            //exit button
            button = makeNavigationButton("toolbarButtonGraphics/general/Stop24.gif", exit, "Exit", "Exit");
            toolBar.add(button);
        //===================================
        protected JButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {
            //Look for the image.
            String imgLocation = imageName;
            URL imageURL = EmailProg.class.getResource(imgLocation);
            //Create and initialize the button.
            JButton button = new JButton();
            button.setActionCommand(actionCommand);
            button.setToolTipText(toolTipText);
            button.addActionListener(this);
            if (imageURL != null) {                      //image found
                button.setIcon(new ImageIcon(imageURL));
            } else {                                     //no image found
                button.setText(altText);
                System.err.println("Resource not found: "+ imgLocation);
            return button;
        //=============================
        public void actionPerformed(ActionEvent e) {
            String cmd = e.getActionCommand();
            String description = null;
            // Handle each button.
            if (exit.equals(cmd)){
                textArea.setText("");
                description = "EXITING";
                System.exit(0);
            if (composemail.equals(cmd)) { //first button clicked
                textArea.setText("");
                description = "Write new mail.";
                composeWindow();
            } else if (sendmail.equals(cmd)) { // second button clicked
                textArea.setText("");
                description = "This button does'nt do anything yet :x";
            } else if (about.equals(cmd)) { // third button clicked
                textArea.setText("");
                description = "About this program. (See pop-up)";
                coolWindow();
            else if (submit.equals(cmd))
                if (cFrom.getText().equals("")||cTo.getText().equals("")||cSubject.getText().equals("")||cMessage.getText().equals(""))
                    textArea.setText("One or more of the fields was not filled in.");
                else{
                      try {
                                String smtpServer="serverhere";
                                String to=cTo.getText();
                                String from=cFrom.getText();
                                String subject=cSubject.getText();
                                String body=cMessage.getText();
                                send(smtpServer, to, from, subject, body);
                                textArea.setText("");
                                description = "Mail Sent.";
                                JOptionPane.showMessageDialog(null, "Message Sent.");
            catch (Exception ex)
                System.out.println("Usage: java com.lotontech.mail.SimpleSender"
                +" smtpServer toAddress fromAddress subjectText bodyText");
                    //CLOSE THE FRAME2 WINDOW IIIIIIIIFFFFFFF SENDING IS SUCCESSFUL!!
                }//end of else during send
           }//end of if of submit
            displayResult(description);
        //============================
        protected void displayResult(String actionDescription) {
            textArea.append(actionDescription + newline);
        //=============================
        public void coolWindow() {
            JFrame frame = new JFrame("About");
            JTextArea filecontents = new JTextArea();
            filecontents.setText("Use the tool bar to compose\n compose new emails, in which you can\n send to anyone on the\n srvhs email server. \n Fill in all the blanks before pressing send. If you dont\n you will receive an error! \n For more information about this program click on the\n information button.");
            frame.getContentPane().add(filecontents, BorderLayout.CENTER);
            frame.pack();
            frame.setResizable(false);
            frame.setSize(300,200);
            frame.setVisible(true);
         //===============================
        public void composeWindow() {
            frame2.getContentPane().setLayout(new GridBagLayout());
            frame2.setResizable(false);
            frame2.setSize(600,500);
            frame2.setVisible(true);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 10, 5, 10);
            cMessage.setLineWrap(true);
            subbutton = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", submit,"submit","submit");
            addRow(gbc, lFrom, cFrom);
            addRow(gbc, lTo, cTo);
            addRow(gbc, lSubject, cSubject);
            addRow(gbc, lMessage, cMessage);
            addRow(gbc, lSubmit, subbutton);
        //===============================
        private void addRow(GridBagConstraints gbc, Component left, Component right) {
            gbc.gridx = GridBagConstraints.RELATIVE;
            gbc.gridy = GridBagConstraints.RELATIVE;
            gbc.gridheight = 1;
            gbc.gridwidth = 1;
            gbc.anchor = GridBagConstraints.EAST;
            frame2.getContentPane().add(left, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;
            frame2.getContentPane().add(right, gbc);
            frame2.pack();
       //=======================
        public static void send(String smtpServer, String to, String from, String subject, String body) {
        try {
          Properties props = System.getProperties();
          props.put("mail.smtp.host", smtpServer);
          Session session = Session.getDefaultInstance(props, null);
          // -- Create a new message --
          Message msg = new MimeMessage(session);
          // -- Set the FROM and TO fields --
          msg.setFrom(new InternetAddress(from));
          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
          // -- We could include CC recipients too --
          // if (cc != null)
          // msg.setRecipients(Message.RecipientType.CC
          // ,InternetAddress.parse(cc, false));
          // -- Set the subject and body text --
          msg.setSubject(subject);
          msg.setText(body);
          // -- Set some other header information --
          msg.setHeader("X-Mailer", "LOTONtechEmail");
          msg.setSentDate(new Date());
          // -- Send the message --
          Transport.send(msg);
          System.out.println("Message sent OK.");
        catch (Exception ex)
          ex.printStackTrace();
        public static void main(String[] args) {
            JFrame frame = new JFrame("EmailProg");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            EmailProg newContentPane = new EmailProg();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    }

  • What do i need to know to send email using Java???

    hi there
    what do i need to know to build an application that sends email? thank you.

    It would also help if you knew something about how Internet e-mail works. Such as what an SMTP server does, what relaying is and why it's bad, and so on.

  • Does any one have a sample code for sending email using IMAP ?

    Hi
    thank you for reading my post
    I have tried to use SMTP and because of some problems i could not use it and i must use Imap (authentication required)
    here is my SMTP code , does any one know how i can tune it to use Imap , or has a code snippet to send email using Imap ?
    thanks
    private static void postMail(String[] recipients, String subject, String message,
                             String from) throws MessagingException {
            boolean debug = false;
            class SMTPAuthenticator extends javax.mail.Authenticator
                    public PasswordAuthentication getPasswordAuthentication()
                        return new PasswordAuthentication(mail_usrname,mail_password);
            //Set the host smtp address
            Properties props = new Properties();
            FileInputStream fis;
            try {
                System.out.println("Loading property file");
                fis = new FileInputStream(new File("c:/email.properties"));
                props.load(fis);
                System.out.println("property file done");
            } catch (FileNotFoundException e) {
                System.out.println("file not found");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("can not read properties file");
                e.printStackTrace();
            /*props.put("mail.smtp.user", mail_usrname);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
            // create some properties and get the default Session
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            // create a message
            Message msg = new MimeMessage(session);
            // set the from and to address
            InternetAddress addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);
            InternetAddress[] addressTo = new InternetAddress[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                addressTo[i] = new InternetAddress(recipients);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/HTML");
    System.out.println(msg.toString());
    Transport.send(msg);

    Please try this out!!!!!!!!!
    You can send emails using Outlook also. You can send email over Microsoft Exchange with this object (or another email server, using IMAP/POP).
    Sub SendMailOutlook(aTo, Subject, TextBody, aFrom)
    'Create an Outlook object
    Dim Outlook 'As New Outlook.Application
    Set Outlook = CreateObject("Outlook.Application")
    'Create e new message
    Dim Message 'As Outlook.MailItem
    Set Message = Outlook.CreateItem(olMailItem)
    With Message
    'You can display the message To debug And see state
    '.Display
    .Subject = Subject
    .Body = TextBody
    'Set destination email address
    .Recipients.Add (aTo)
    'Set sender address If specified.
    Const olOriginator = 0
    If Len(aFrom) > 0 Then .Recipients.Add(aFrom).Type = olOriginator
    'Send the message
    .Send
    End With
    End Sub

  • How to send sms to mobile from tomcatserver using java code?

    Hi,
    Could you please let me know that,
    How to send sms to mobile from tomcatserver using java code? Please provide the code snippet.
    Thanks in advance.

    Yes, but something needs to send that message. You can't just take an arbitrary computer and send an SMS, it does not have the hardware to do that.
    So either you have a mobile through which you do that or more likely - you use some sort of online service to do it. Whatever choice you make will determine what code you will have to write to get it done. Nobody is going to deliver the code to you, that's your job. It is also your job to figure out what service you are going to use.

  • Error while sending email using TemplateEmailSender in CSC server

    Hi,
    We are trying to send email using TemplateEmailSender from CSC server. But it is giving Null Pointer Exception in ProfiledMessageSource like below. The same code is working fine in commerce instance but it is failing in CSC instance. We are using ATG2007.1p3
    Any pointers would be helpful.
    Below is the error.
    Error while sending email
    java.lang.NullPointerException
            at atg.userprofiling.dms.ProfiledMessageSource.isConfiguredForProfileSubject(ProfiledMessageSource.java:196)
            at atg.userprofiling.dms.DPSMessageSource.fireEndSessionMessage(DPSMessageSource.java:864)
            at atg.userprofiling.dms.DPSMessageSource.fireEndSessionMessage(DPSMessageSource.java:848)
            at atg.userprofiling.SessionEventTrigger.nameContextElementPreUnbound(SessionEventTrigger.java:553)
            at atg.nucleus.GenericContext.sendPreUnboundEvent(GenericContext.java:200)
            at atg.nucleus.GenericContext.preNotifyRemovedObject(GenericContext.java:528)
            at atg.nucleus.GenericContext.removeElement(GenericContext.java:566)
            at atg.servlet.SessionNameContext.unbindFromNameContext(SessionNameContext.java:557)
            at atg.servlet.SessionNameContext.stopSession(SessionNameContext.java:534)
            at atg.servlet.SessionNameContext.decrementWrapperCount(SessionNameContext.java:242)
            at atg.servlet.SessionBindingReporter.valueUnbound(SessionBindingReporter.java:206)
            at org.apache.catalina.session.StandardSession.removeAttributeInternal(StandardSession.java:1625)
            at org.apache.catalina.session.StandardSession.expire(StandardSession.java:749)
            at org.apache.catalina.session.StandardSession.expire(StandardSession.java:655)
            at org.apache.catalina.session.StandardSession.invalidate(StandardSession.java:1100)
            at org.apache.catalina.session.StandardSessionFacade.invalidate(StandardSessionFacade.java:150)
            at atg.userprofiling.email.TemplateInvoker$TemplateSession.endSession(TemplateInvoker.java:935)
            at atg.userprofiling.email.TemplateEmailSender.createMessage(TemplateEmailSender.java:2387)

    Thanks for the reply.
    My issue is fixed now. It is JBOSS configuration issue. Sessions are not maintained properly that's why we are getting NULL profile in the session. Our application has multiple WARs so we fixed it by setting emptySessionPath to TRUE. If emptySessionPath attribute in server.xml is false, then each WAR will have its own jsessionid cookie.
    I did not touch ProfiledMessageSource as its required for session triggering.

  • Error in sending mail Using java application using SMTP.

    Hi,
    I have created a java application of self user registration which also sends email to the user.
    I have also added two JAR files ie mail.jar and activation.jar under the PORTAL_INF/lib.
    The code works well in other servers but its showing the error-
    java.lang.NoSuchMethodError: com.sun.activation.registries.MailcapFile.getMailcapList(Ljava/lang/String;)Ljava/util/Map;
    Thanks & Regards,
    Amarys.

    Hi Amarys,
    Please check if you have configure the mail server in SAP protal.
    Refer to below documents:
    [Send email, using SMTP on remote host|Send email, using SMTP on remote host]
    [Mailing throw webdynpro for java|Mailing throw webdynpro for java]
    Best Regards
    Arun Jaiswal

  • Sending email using CL_BCS in the background with subject line 255 chars

    Hello Gurus,
           Following is the sample code,. When I run in the foreground, I am getting the mail, with proper subject line. However my output medium type is '5-'External Send#. When I am trying to run this in my output program, it is resulting in dump.
           When I keep 'COMMIT WORK',  I am getting a dump saying tText * Invalid COMMIT WORK in an update function module.*
           When I remove this 'COMMIT WORK', I am still getting the error, saying Screen output without connection to user. (The current ABAP program "SAPLSTXC" statements could not be executed.)
          Hoping for a quick solution.
    Regards,
    Shaheen
    REPORT  Z_CL_BCS_TEST.
    * Trying classes
    DATA: send_request        TYPE REF TO cl_bcs.
    DATA: li_main_text        TYPE bcsy_text,
          lw_main_text        LIKE LINE OF li_main_text.
    DATA: document            TYPE REF TO cl_document_bcs.
    DATA: recipient           TYPE REF TO if_recipient_bcs.
    DATA: sender              TYPE REF TO if_sender_bcs.
    DATA: l_mtitle            LIKE sodocchgi1-obj_descr.
    DATA: sent_to_all         TYPE os_boolean.
    DATA: bcs_exception       TYPE REF TO cx_bcs.
    DATA: lv_sub TYPE string.
    TRY.
    *     -------- create persistent send request ------------------------
        send_request = cl_bcs=>create_persistent( ).
    *     -------- create and set document---------------
    *     Email title
        l_mtitle = 'attachment'.
        lv_sub = 'Email Title : I want to try for a subject which is more than 50 chars. will this work?'.
        CALL METHOD send_request->set_message_subject
          EXPORTING
            ip_subject = lv_sub.
    *     Fill the body of the mail
        REFRESH li_main_text.
        lw_main_text = 'This is test email'.
        APPEND lw_main_text TO li_main_text.
        CLEAR: lw_main_text.
        lw_main_text = 'Regards'.
        APPEND lw_main_text TO li_main_text.
        CLEAR: lw_main_text.
    *     Create Email Object
        document = cl_document_bcs=>create_document(
          i_type    = 'RAW'
          i_text    = li_main_text
          i_subject = l_mtitle ).
    *     Add document object to send request
        send_request->set_document( document ).
    *     add recipient (e-mail address)
        recipient =
            cl_cam_address_bcs=>create_internet_address(
                  'Shaheen.Taori at solvay.com' ).           " changed the email id purposefully
    *     Add recipient object to send request
        CALL METHOD send_request->add_recipient
          EXPORTING
            i_recipient = recipient
            i_express   = 'X'.
    *     ---------- send document ---------------------------------------
    *    sent_to_all = send_request->SEND_WITHOUT_DIALOG( I_WITH_ERROR_SCREEN = ' ').
        CALL METHOD send_request->SEND_WITHOUT_DIALOG.
    *      EXPORTING
    *        e_sent_to_all = 'X'.
    *    IF sent_to_all IS INITIAL.
    *      MESSAGE 'Erorr while sending email ' TYPE 'E'.
    *      EXIT.
    *    ENDIF.
          COMMIT WORK.
    *   exception handling
      CATCH cx_bcs INTO bcs_exception.
        MESSAGE i865(so) WITH bcs_exception->error_type.
    ENDTRY.

    Try using method SEND instead of SEND_WITHOUT_DIALOG.
    Also try calling method SET_SEND_IMMEDIATELY before calling method SEND.
    Use below code lines,
    send_request->set_send_immediately( i_send_immediately = 'X' ).
    sent_to_all = send_request->send( i_with_error_screen = 'X' ).   " Instead of CALL METHOD send_request->SEND_WITHOUT_DIALOG.

  • How to send attachments using java application and outlook

    Hi ,
    I created an application in java which is as
    on the Conference Tab i can schedule a conference and with the send command on page it map all the scheduled data to outlook(with all conference details) and using outlook send option the mails are send to appropriate user.
    but now i want to modify this application such as when i use the send command from my jsp page it should attach the file that is in .vcs or .ics format for auto updation of user calender.
    can any one know how to send attachment using java application .

    Last time I checked, SMS was a service between carriers and doing SMS yourself was really tricky. Some services existed to let you do it but as I recall they wanted non-trivial money.
    However, most phone carriers provide an email-to-SMS bridge of some kind.
    So the easiest thing is just to send an email.
    That's sending from a non-phone to a phone. There's a J2ME library to send/receive SMS from/to a phone.
    However, this is from memory, and a little out of date, so I could be entirely wrong. Hope it helps anyway.

  • Sending Emails With Java

    I'm trying to find out how to send emails with java - without using the java mail api - i've been told there is a way to do it but i cant seem to find it - any help on this would be gratefully recieved as i'm totally stuck! :(

    Ok, I expanded on it a little bit. Still probably isnt totally correct.
    String localhost="yourdomain.com";
    String sendMailHost=�mail.domain.com�;
    int portNo=25;
    String from="[email protected]";
    String to="[email protected]";
    String message=�Message Body.�;
    Socket s = new Socket(SendMailHost,portNo);
    DataInputStream in = new DataInputStream(s.getInputStream() ) ;
    PrintStream out = new PrintStream(s.getOutputStream() ) ;
    out.println("HELO " + locahost);
    out.flush() ;
    in.readLine(); //ignore response
    out.println("MAIL FROM:  " + from);
    out.flush() ;
    in.readLine(); //ignore response
    out.println("RCPT TO:  " + to);
    out.flush() ;
    in.readLine(); //ignore response
    out.println("DATA");
    out.println(message);
    out.println(�.�);
    s.close();

Maybe you are looking for

  • Guitar audio drop-out at lower volumes

    I have tried out mainstage on a friends macbook pro, to check if it will be worth an investment into Logic over Garageband, mainly as an effects emulator for my guitar so I don't need to worry about amps in my small flat.   I connected through an Edi

  • PSE 13 freezing when selecting the Graphics icon at the bottom right of Expert screen

    I installed PSE 13 today and was checking out the changes from 11, my prior version, which is still installed, fortunately, and when I select the Graphics icon at the bottom right of the screen, the program freezes completely.  Has anybody else had t

  • Payment details requesting six digit pin and 3d, w...

    Help I've been sent a request for payment details and they want a six digit pin and 3d. How do I get these?

  • Organization data from ECC to CRM

    Hi Experts, We need to download organization data from ECC to CRM, and our requirement is to download two different kinds of org structures, sales org structure and HR org structure. Could you please advise whether this is possible in the system and

  • Scheduling Mappings and Process Flows

    Can you please tell me how to schedule mappings and process flows in a little detail, if any one has done that. I think OEM can be used for this but dont have any clear cut idea of doing it. Can the mappings/process flows be scheduled without using O