Sunday, June 29, 2008

Sending email messages in Delphi

Learn how to send email messages with attachments using Indy and Delphi. Full source code to a simple "SMTP Mail Sender" application included.

Let's get straight to the problem ... suppose you have an application that operates on some database data, among other tasks, users need to export data from your application and send the data attached to an email address (to you, an error report, for example). For the moment, you are exporting data to an external file, and than Outlook (Express) is being used to send the email.

Let's see how create a more powerful application by including an option to send email messages, with attachments, directly from your Delphi application.

Go email, go
There are many ways you can send an email directly from Delphi, the most simple one is to use the ShellExecute API call to send an email using the default e-mail client software installed on a user's machine, this approach is ok, but you are unable to send attachments in this way. Another technique uses MS Outlook and OLE to send email with attachment, this one requires that Outlook is installed. Another approach is to use Delphi's built-in support for the Windows Simple Mail API (only works if the end-user has MAPI-compliant email software).

The approach we are discussing here uses Indy components - a great internet component suite comprised of popular internet protocols written in Delphi and based on blocking sockets.

The TIdSMTP (Indy) way
Sending (or retrieving) email messages with Indy components (ship with Delphi 6+) is as easy as dropping a component or two on a form, setting some properties, and "clicking a button".

To send an email with attachment(s) from Delphi using Indy, we'll need two components. First, the TIdSMTOP is used to connect and communicate (send mail) with an SMTP server. Second, the TIdMessage handles storing and encoding of message(s).
When the message is constructed (TIdMessage "filled" with data), the email message is delivered to an SMTP server using the TIdSMTP.

Mail sender
I've created a simple mail sender project; you can download the full source code.

As you can see from the design-time screen shot, to send an email using the TIdSMTP component, you at least need to specify the SMTP mail server (host). The message itself needs the "From", "To", "Subject", ..., and all other parts you've accustomed with.

Here's the code that handles sending one email message with attachment:

procedure TMailerForm.btnSendMailClick(Sender: TObject);
begin
StatusMemo.Clear;

//setup SMTP
SMTP.Host := ledHost.Text;
SMTP.Port := 25;

//setup mail message
MailMessage.From.Address := ledFrom.Text;
MailMessage.Recipients.EMailAddresses :=
ledTo.Text + ',' + ledCC.Text;

MailMessage.Subject := ledSubject.Text;
MailMessage.Body.Text := Body.Text;

if FileExists(ledAttachment.Text) then
TIdAttachment.Create(MailMessage.MessageParts,
ledAttachment.Text);

//send mail
try
try
SMTP.Connect(1000);
SMTP.Send(MailMessage);
except on E:Exception do
StatusMemo.Lines.Insert(0, 'ERROR: ' + E.Message);
end;
finally
if SMTP.Connected then
SMTP.Disconnect;
end;

end; (* btnSendMail Click *)

Note: inside the source code, you'll find two extra procedures - used to make the values of the "Host", "From" and "To" edit boxes persistent, using an INI file
for storage

/resource from http://delphi.about.com/


Read more!!!

Examples of Sending Email in C#

In order to send email in C# code, do the following:

// create mail message object
MailMessage mail = new MailMessage();
mail.From = ""; // put the from address here
mail.To = ""; // put to address here
mail.Subject = ""; // put subject here
mail.Body = ""; // put body of email here
SmtpMail.SmtpServer = ""; // put smtp server you will use here
// and then send the mail
SmtpMail.Send(mail);


Here is an another example

// Send a quick e-mail message
SendEmail.SendMessage("This is a Test", "This is a test message...", "noboday@nowhere.com", "somebody@somewhere.com", "ccme@somewhere.com");


Here is a full code of sending email

//This sample demonstrates how to send email in CSharp
using System;
using AOSMTPLib;

namespace CSharpSample
{
class SendEmail
{
public static void Main( string[] args )
{
AOSMTPLib.MailClass SMTP = new AOSMTPLib.MailClass(); //create component instance
//If you don't specify the value of ServerAddr property,
//ANSMTP would simulate a smtp server to send email automatically.
SMTP.ServerAddr = "smtp.component.com"; //email server
SMTP.FromAddr = "Asp@component.com"; //sender' email address
SMTP.AddRecipient( "Dennis", "Dennis@component.com", 0 ); //normal recipient
SMTP.BodyFormat = 1; //html format
SMTP.Subject = "send email asp asp.net, smtp, control, dotnet"; //email subject
SMTP.BodyText =".... ocx, library, activex, component, NET assemble";//body
if( SMTP.SendMail() == 0 )//send email
Console.WriteLine( "Email delivered");
else
Console.WriteLine( SMTP.GetLastErrDescription() );
}
}
}


Read more!!!

Friday, June 27, 2008

Download Files from Web in C#

This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file.

Download File Synchronously

The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");


Download File Asynchronously

To download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.

private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}


Note: Although you use asynchronous method, it can block the main thread for a while. It's because before the async download itself, it checks the DNS name (in this case „mysite.com“) and this check is done internally by blocking function. If you use directly IP instead of domain name, the DownloadFileAsync method will be fully asynchronous.

/resource from http://www.csharp-examples.net/


Read more!!!

How to implement MD5 encryption in C#.

The way is very simple shown below.

System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s =
new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
password = s.ToString();

And also there is the simplest and fastest version that actually works

public static string EncodePassword(string password)
{
byte[] original_bytes = System.Text.Encoding.ASCII.GetBytes(password);
byte[] encoded_bytes = new MD5CryptoServiceProvider().ComputeHash(original_bytes);
StringBuilder result = new StringBuilder();
for (int i=0; i < encoded_bytes.Length; i ) {
result.Append(encoded_bytes[i].ToString("x2"));
}
return result.ToString();
}


Read more!!!

Friday, June 20, 2008

Another document about UML

Read this document on Scribd: What is UML


Read more!!!

UML lesson No.9-2

Read this document on Scribd: 09 UML InteractionDiagrams(2)


Read more!!!

UML lesson No.9-1

Read this document on Scribd: 09 UML InteractionDiagrams


Read more!!!

UML lesson No.8

Read this document on Scribd: 08 UML ClassDiagram


Read more!!!

UML lesson No.7

Read this document on Scribd: 07 UML CRC


Read more!!!

UML lesson No.6

Read this document on Scribd: 06 UML DomainModel


Read more!!!

UML lesson No.5

Read this document on Scribd: 05 UML Elab%26SSD


Read more!!!

UML lesson No.3

Read this document on Scribd: 03 UML UseCaseDiagram


Read more!!!

UML lesson No.2

Read this document on Scribd: 02 UML UseCase


Read more!!!

UML lesson No.1

Read this document on Scribd: 01 UML Intro


Read more!!!