Email Sending with Attachment in Java

email

 

That is for sending Email using “mail.smtp.auth”

public static String sendEmail(final String username, final String password, String replyto, String port, String host, String from, String to, String messagesubject, String messageboday, String attactmentpath) {

//   final String username = “zakhter@truemeridian.com”;
//  final String password = “password”;

Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
//props.put(“mail.smtp.starttls.enable”, “true”);
props.put(“mail.smtp.host”, host);//”smtp.truemeridian.com”);
props.put(“mail.smtp.port”, port);
props.setProperty(“mail.smtp.ssl.trust”, host);

Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));//”zakhter@truemeridian.com”));
message.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(to));//”zeeshanakhter2009@gmail.com”));

InternetAddress replyAddresses[] = new InternetAddress[1];
replyAddresses[0] = new InternetAddress(replyto);
message.setReplyTo(replyAddresses);
message.setSubject(messagesubject);
message.setText(messageboday);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageboday);

// Create a multipar message
Multipart multipart = new MimeMultipart();

// Set text message part
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(attactmentpath);
messageBodyPart.setDataHandler(new DataHandler(source));
attactmentpath = attactmentpath.replace(“\\”, “/”);
String[] fileName = attactmentpath.split(“/”);
System.out.println(“\n\nPath3=” + attactmentpath);
// for(int i=0;i
// {
//    attactmentpath=fileName[i];
// }
attactmentpath = fileName[fileName.length – 1];
messageBodyPart.setFileName(attactmentpath);
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts
message.setContent(multipart);
message.setContent(multipart);

Transport.send(message);

System.out.println(“Done”);

return “Sent”;
} catch (Exception e) {
e.printStackTrace();
return “Fail”;
}
}

 

How to import large sql files into mysql using phpmyadmin wamp server

MySQL

Stop all services in wamp.

Then make changes to php.ini

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
max_allowed_packet = 200M (in mysql  my.ini  file)

Restart all services and it should be okay,

Now  XXXMb file upload very quickly.

 

Deploying Java Servlet applications on Windows with IIS

IIS

Java platform is extremely successful in building robust and high performance web applications. Platform independence is one of the strength of Java engine and Helicon Zoo now provides a convenient way to deploy and run Java web applications on Windows platform with Microsoft IIS. To deploy Java Servlet application on IIS 7 you will only need to follow this simple instruction:

Platfrom installation

  1. Download and install Web Platform Installer.
  2. Run Web Platform Installer and click “Options”.
  3. Add Helicon Zoo feed into Display additional scenarios box:  http://www.helicontech.com/zoo/feed. New “Zoo” tab will appear.
  4. Go to the Zoo, Packages and install Java Hosting Package.
  5. Accept licenses to start installation process.

Alternatively, instead of installing Java Hosting Package you can install Modules –> Helicon Zoo Module and Engines –> Jetty separately. This is minimal requirement to run Java Servlet applications under Microsoft IIS web server. If you want to run Java Servlets under IIS Express and WebMatrix in your development environment, then you will also need to install Helicon Zoo Module for IIS Express form Engines section.

This is enough configuration to run most of Java Servlet applications directly form IIS.

Installing application

Launch IIS Manager and create new web-site or an application within a web-site. Copy your Java application into the root folder of this IIS application. Java application could be either a single .war file or set of unpacked files with directory structure, including web-inf folder. Then just create the following web.config:

 <?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <heliconZoo>
      <application name="jetty.project" >
        <environmentVariables>
          <!-- Uncomment line below if you want to set contexts directory -->
          <!--  <add name="CONTEXTS_DIR" value="%APPL_VIRTUAL_PATH%" /> -->

          <!-- Optional variables: -->
          <!-- <add name="CONTEXT_PATH" value="%APPL_VIRTUAL_PATH%" /> -->
          <!-- <add name="WAR_EXTRACT_PATH" value="%APPL_PHYSICAL_PATH%" /> -->

          <!-- A WAR file or start directory to run -->
          <add name="WAR_FILE" value="my_application.war" />
        </environmentVariables>
        </application>
    </heliconZoo>

        <handlers>
          <add name="jetty.project#x86" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x86"
            preCondition="bitness32" resourceType="Unspecified"
            requireAccess="Script" />
          <add name="jetty.project#x64" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x64"
            preCondition="bitness64" resourceType="Unspecified"
            requireAccess="Script" />
        </handlers>
  </system.webServer>
</configuration>

Please take a look at <environmentVariables> section.

  • CONTEXTS_DIR — optional path to directory with .xml files which describe Jetty contexts. If this variable isn’t set, Zoo looks for “contexts” folder in the root of application. If no such folder found, Zoo presumes the application has single context and uses variables described below.
  • CONTEXT_PATH — optional virtual path of the application. Default value is taken from APPL_VIRTUAL_PATH variable.
  • WAR_FILE — optional path to a .war file or directory with extracted application.
  • WAR_EXTRACT_PATH — optional .war file extraction path. Is set to application’s root folder by default.

Here is an example of context.xml file that you may use instead of setting WAR file name explicitly. This allows to run multiple applications and contexts in a single IIS web site.

contexts/context.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">

   <Set name="contextPath">/application</Set>
   <Set name="war">my_application.war</Set>
   <Set name="tempDirectory">application_dir</Set>

</Configure>

WARNING: Since WAR files need to be extracted before execution you will need to have a folder with write permissions.  In default IIS installation all application pools are executed with permissions of IIS_IUSRS group which does not have write permissions to the web application folders. You will need to provide write permissions to the user running Application Pool or IIS_IUSRS group to the folder containing Java application or specify other folder using WAR_EXTRACT_PATH variable with write permissions provided.Now you can open IIS web site in the browser and see your Java web application running.

That’s it! Installation process is clear and automatic and will only take several minutes.

5 Responses to Deploying Java Servlet applications on Windows with IIS

  1. Peter says:

    Downloaded and installed as described in the article (http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/).

    However for some weird reason I can successfully view the Java app via IIS when using http://localhost/appname but if I do the same thing http:///appname on another machine I get a a 404 from IIS and if I do it on the server itself I get a 404 from Jetty instead.

    This is running on a 64bit Win2008R2 Std server VM with an IIS app set up to use a ASP.NET 4.0 integrated app pool.
    The folder the IIS app points to contains the contents of the WAR file, i.e. \web-inf and \xforms-jsp and the web.config with the described contents from the article.

    Any ideas on what could be wrong would be much appreciated.

    • Slavik says:

      Hello.
      Please try and use CONTEXT_PATH variable as follows:
      <add name=”CONTEXTS_PATH” value=”/appname” />

      Make sure “appname” is an application. If it’s not, open IIS manager, navigate to that folder and in the context menu click “Convert to Application”.

  2. jules says:

    I installed on a Windows 7 64 bit machine and then downloaded the jenkins.war file and tried to deploy it:
    But I get:
    HTTP ERROR: 503
    Problem accessing /test. Reason:
    Service Unavailable
    Powered by Jetty://

    ??

    • Slov says:

      I think installing Jenkins on IIS may deserve a separate article.
      First you will need to upgrade your Jetty installation as we have fixed some functions. Just delete C:\jetty folder and install again using Helicon Zoo feed.
      Then you will need to use contexts folder, instead of setting WAR file explicitly as Jenkins require additional configurations.
      Please remove all “environmentVariables” from web.config, create contexts folder, and create context.xml file in this folder with the following content:

      < ?xml version=”1.0″?>
      < !DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”&gt;

      Test Realm
      /jenkins
      jenkins.war

      After that navigate to http://localhost/jenkins (not to the root folder). It should work now.

      • Slov says:

        A bug with tags. Try again:

        <?xml version=”1.0″?>
        <!–DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”>–>

        <Configure class=”org.eclipse.jetty.webapp.WebAppContext”>
        <Get name=”securityHandler”>
        <Set name=”loginService”>
        <New class=”org.eclipse.jetty.security.HashLoginService”>
        <Set name=”name”>Test Realm</Set>
        </New>
        </Set>
        </Get>

        <Set name=”contextPath”>/jenkins</Set>
        <Set name=”war”>jenkins.war</Set>
        <Set name=”tempDirectory”>jenkins</Set>
        </Configure>

Reference :http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/

Program to develop a Mail Client in Java.

English: SMTP transfer model Blue arrows can b...

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class MailClient
{
public static void main(String []args)
{
JFrame frame = new MailClientFrame();
frame.show();
}
}
class MailClientFrame extends JFrame implements ActionListener
{

private BufferedReader in;
private PrintWriter out;
private JTextField from;
private JTextField to;
private JTextField smtpServer;
private JTextArea message;
private JTextArea response;
private JLabel fromLbl;
private JLabel toLbl;
private JLabel serverLbl;

public MailClientFrame()
{
setTitle(“Mail Client”);
setSize(250,400);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);

getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

fromLbl = new JLabel(“From: “);
getContentPane().add(fromLbl);

from = new JTextField(20);
getContentPane().add(from);

toLbl = new JLabel(“To: “);
getContentPane().add(toLbl);

to = new JTextField(20);
getContentPane().add(to);

serverLbl = new JLabel(“SMTP Server:”);
getContentPane().add(serverLbl);

smtpServer = new JTextField(20);
getContentPane().add(smtpServer);

message = new JTextArea(5,20);
getContentPane().add(message);

JScrollPane p = new JScrollPane(message);
getContentPane().add(p);

response = new JTextArea(5,20);
getContentPane().add(response);

JScrollPane p1 = new JScrollPane(response);
getContentPane().add(p1);

JButton sendButton  = new JButton(“Send”);
sendButton.addActionListener(this);

JPanel buttonPanel = new JPanel();
buttonPanel.add(sendButton);

getContentPane().add(sendButton);

}

public void actionPerformed(ActionEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
sendMail();
}
}
);
}

public void sendMail()
{
try
{
Socket s = new Socket(smtpServer.getText(),25);
out  = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(s.getInputStream()));

String hostName = InetAddress.getLocalHost().getHostName();
send(null);
send(“HELO” + hostName);
send(“MAIL FROM:”+ from.getText());
send(“RCPT TO:” + to.getText());
send(“DATA”);
out.println(message.getText());
send(“.”);
s.close();
}
catch(IOException e)
{
response.append(“Error:” + e);
}
}

public void send(String s) throws IOException
{
if(s!=null)
{
response.append(s+”\n”);
out.println(s);
out.flush();
}
String line;
if ( (line = in.readLine())!=null)
{
response.append(line+”\n”);
}
}
}

C# Chat: Part 1 – Building the Chat Client

Download this Visual Studio 2005 project Download the Chat Client Application project(Visual Studio 2005)

Building a Chat Server and a Chat Client

To no avail I’ve been searching the web for a good C# chat client/server application that is not thousands of lines of code long. The only simple ones I could find were flawed or very buggy, but then again I tried to combine the good parts of all the tutorials I found into one application, and one tutorial that you can see here today. We are going to build a fairly larger application (a few hundred lines of codes) than the ones we’re used to here on Geekpedia, but we’re still going to keep it simple. In fact, there will be two applications: one is a chat server, that handles incoming connections, stores them in hash tables, and distributes new messages to everyone connected, and the other is of course, the chat client, which connects to the server, sends messages and listens for incoming messages. A little knowledge of C#’s networking objects, multi-threading, events and delegates will definitely help you understand this tutorial more easily. A good way to start learning about delegates, events and creating client-server applications is to read the Delegates and Events in C# tutorial first.
The chat server will be able to accept as many chat clients as allowed by the hash table (and you are able to define the limit of the hash table yourself), and it will also track all the messages that are going back and forth in its own chat window, so you should be able to scale this code to a full blown chat application as long as you add the necessary error handling and the bells and whistles.

 

The client application

The client application is, as you might have expected, the simpler one, since all it has to do is to attempt to connect to the chat server, request an username, start listening for messages and sending its own, and finally disconnecting.
Start Visual Studio 2005 and create a new C# Windows Application. I’ve given mine the obvious “Chat Client” name.

Chat Client Form

The first two TextBoxes (txtIp and txtUser) will hold the IP address of the server we want to connect to and the desired username. Before testing out this code keep in mind to change this IP address to the one of the computer in your network that runs the client. If you read the Delegates and Events in C# tutorial, you probably assume you can run the chat application and the server application on the same machine, without needing two different computers connected through a network or the Internet. And you would be right.
The Connect (btnConnect) and Send (btnSend) buttons are obvious, they’re for connecting to the server and sending messages. The large multi-line TextBox is named txtLog and it is where all the messages will be shown.The small TextBox at the bottom is called txtMessage and it is where the message to be sent to the server will be typed.

Now that we’re done with the actual design of the form, we can finally code. Since we will be making use of networking, streaming and threading objects, start by adding the following using statements:

using System.Net;

using System.Net.Sockets;

using System.IO;

using System.Threading;

We’re going to declare most of our objects inside the class, as private, since we don’t need them accessible from anywhere else outside the class:

// Will hold the user name

private string UserName = “Unknown”;

private StreamWriter swSender;

private StreamReader srReceiver;

private TcpClient tcpServer;

// Needed to update the form with messages from another thread

private delegate void UpdateLogCallback(string strMessage);

// Needed to set the form to a “disconnected” state from another thread

private delegate void CloseConnectionCallback(string strReason);

private Thread thrMessaging;

private IPAddress ipAddr;

private bool Connected;

And now that we have them declared, let’s put them to use. Let’s start with the btnConnect_Click event which can be automatically generated if you double click on the Connect button. Inside it we’re going to check whether or not we are connected to a server. If we are, we should call the method that initializes the connection, otherwise we call the method that closes the connection, also specifying a reason why to it:

private void btnConnect_Click(object sender, EventArgs e)

{

// If we are not currently connected but awaiting to connect

if (Connected == false)

{

// Initialize the connection

InitializeConnection();

}

else // We are connected, thus disconnect

{

CloseConnection(“Disconnected at user’s request.”);

}

}

All simple so far, so let’s move to InitializeConnection():

private void InitializeConnection()

{

// Parse the IP address from the TextBox into an IPAddress object

ipAddr = IPAddress.Parse(txtIp.Text);

// Start a new TCP connections to the chat server

tcpServer = new TcpClient();

tcpServer.Connect(ipAddr, 1986);

 

// Helps us track whether we’re connected or not

Connected = true;

// Prepare the form

UserName = txtUser.Text;

 

// Disable and enable the appropriate fields

txtIp.Enabled = false;

txtUser.Enabled = false;

txtMessage.Enabled = true;

btnSend.Enabled = true;

btnConnect.Text = “Disconnect”;

 

// Send the desired username to the server

swSender = new StreamWriter(tcpServer.GetStream());

swSender.WriteLine(txtUser.Text);

swSender.Flush();

 

// Start the thread for receiving messages and further communication

thrMessaging = new Thread(new ThreadStart(ReceiveMessages));

thrMessaging.Start();

}

Nothing too complicated happens in there. The IP address is parsed from the TextBox into an IPAddress object, and then we open a TCP connection to that address. The port is 1986 but it makes no difference as long as its free. We then prepare the controls on the form by disabling some and enabling the others. We also change the caption of btnConnect to now say Disconnect. Through a stream, we then tell the server which username we want, and immediately after that we start a new thread that calls the method ReceiveMessages() which will listen for incoming messages from now on. By putting this in a separate thread, our application is still fully usable while it is listening for messages from the server and keeping the connection alive.

It’s time to see what the ReceiveMessages() method is all about:

private void ReceiveMessages()

{

// Receive the response from the server

srReceiver = new StreamReader(tcpServer.GetStream());

// If the first character of the response is 1, connection was successful

string ConResponse = srReceiver.ReadLine();

// If the first character is a 1, connection was successful

if (ConResponse[0] == ‘1’)

{

// Update the form to tell it we are now connected

this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { “Connected Successfully!” });

}

else // If the first character is not a 1 (probably a 0), the connection was unsuccessful

{

string Reason = “Not Connected: “;

// Extract the reason out of the response message. The reason starts at the 3rd character

Reason += ConResponse.Substring(2, ConResponse.Length – 2);

// Update the form with the reason why we couldn’t connect

this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });

// Exit the method

return;

}

// While we are successfully connected, read incoming lines from the server

while (Connected)

{

// Show the messages in the log TextBox

this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });

}

}

A new stream reader is hooked up to the TCP client. It will listen for incoming messages. But first of all, we read the first line coming from the server. The reason for that is that we know the first line contains a response telling us whether or not we connected successfully. Two reasons why we might’ve not connected successfully are if we attempted to use an username that is already taken, or if we attempted to use Administrator as the username, which is reserved for obvious purposes. The first character of the response given by the server tells us through a 1 that the connection was successful, and through a 0 if it was unsuccessful. And in that case, it also reads a reason as to why it was unsuccessful. That reason starts at the 3rd character of the message, since the first one is the number, and the second one is a pipe character. For example: 0|Username is already in use. Now you can see why if the first character is not a 1 we read the string that starts at the 3rd character and ends at the end of the line.

The this.Invoke() calls tell the form to update itself. We can’t directly update the form elements ourselves from this method because it’s in a separate thread (remember we called it using ThreadStart()) and cross-thread operations are illegal.

Finally, the while (Connected) loop keeps calling the srReceiver.ReadLine() method which checks for incoming messages from the server.

Next comes the method that we kept calling using this.Invoke() – all it does is to update the txtLog TextBox with the latest message:

// This method is called from a different thread in order to update the log TextBox

private void UpdateLog(string strMessage)

{

// Append text also scrolls the TextBox to the bottom each time

txtLog.AppendText(strMessage + “\r\n”);

}

So far we’ve seen how to receive messages from the server, but nothing about how to send them. When do we want to send a message? When the Send button is clicked or when the Enter key is pressed while txtMessage has the focus. This should be hooked up to the Click event of the btnSend button:

// We want to send the message when the Send button is clicked

private void btnSend_Click(object sender, EventArgs e)

{

SendMessage();

}

And this needs to be hooked up to the KeyPress event of txtMessage:

// But we also want to send the message once Enter is pressed

private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)

{
// If the key is Enter

if (e.KeyChar == (char)13)

{

SendMessage();

}

}

You can see that both of them make a call to SendMessage, which we are going to see next:

// Sends the message typed in to the server

private void SendMessage()

{

if (txtMessage.Lines.Length >= 1)

{

swSender.WriteLine(txtMessage.Text);

swSender.Flush();

txtMessage.Lines = null;

}

txtMessage.Text = “”;

}

Quite simple, isn’t it? It just checks for the number of lines to be greater or equal to 1, and then writes that line to the TCP connection through the StreamWriter object. Calling Flush() ensures that the messages are being sent right away.

We seem to be almost done with the client application. But let’s not forget that when btnConnect was clicked, if we were already connected, we called a method called CloseConnection() – what happened to that? Well here it is:

// Closes a current connection

private void CloseConnection(string Reason)

{

// Show the reason why the connection is ending

txtLog.AppendText(Reason + “\r\n”);

// Enable and disable the appropriate controls on the form

txtIp.Enabled = true;

txtUser.Enabled = true;

txtMessage.Enabled = false;

btnSend.Enabled = false;

btnConnect.Text = “Connect”;

 

// Close the objects

Connected = false;

swSender.Close();

srReceiver.Close();

tcpServer.Close();

}

The form is being brought back to the not-connected state, and the TCP connection and streams are being closed. But what happens if the user doesn’t click Disconnect and just closes the application while the connection with the server is alive? We surely don’t want to leave the connection open like this till it dies by its own. Thankfully there is the ApplicationExit event that fires when the application closes, and that’s where we can close our connection. To hook up the event change your Form1 constructor to the following:

public Form1()

{

// On application exit, don’t forget to disconnect first

Application.ApplicationExit += new EventHandler(OnApplicationExit);

InitializeComponent();

}

And here is the event handler that does the actual disconnection:

// The event handler for application exit

public void OnApplicationExit(object sender, EventArgs e)

{

if (Connected == true)

{

// Closes the connections, streams, etc.

Connected = false;

swSender.Close();

srReceiver.Close();

tcpServer.Close();

}

}

Believe or not, we’re done with the chat client application. You should be able to compile and run it now, but of course there’s nothing to connect to because we haven’t developed the server. But that comes next in C# Chat: Part 2- Building the Chat Server. Here’s a little teaser of our applications in action, with the server in the shadow of the two:

Chat Clients