Wednesday, March 14, 2007

Send a authenticated mail in .NET2.0(C#)

Using following coding you can send an email to any mail server and if you want you could modify the code to send a automatic mail using smtp server. If your machine connected to a LAN and you have a particular Email address for your domain, normally the main mail server do not allow you to programmatically send a simple mail to other mail servers.
In order to do that you have to authnticate with your existing mail account username and password. But you can send a mail anonymously to any mail address.You have to specify the smtp server name(Your mail server name). This code can run on .NET2.0 framework, I have tried and its properly working.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;

namespace test
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

public void SendMail()
{

string strFrom = "";
string strTo = "";
string strMsg = "";
string strSubjet = "";
strFrom = t_from.Text.ToString().Trim();
strTo = t_mobile.Text.ToString().Trim();
strMsg = t_msg.Text.ToString().Trim();
strSubjet = t_subject.Text.ToString().Trim();

//Builed The MSG
System.Net.Mail.MailMessage msg =new System.Net.Mail.MailMessage();
// msg.To.Add("xxxxx@gmail.com");

msg.To.Add(strTo);
msg.From = new MailAddress("Anonymous_name@xxxxx.com",
strFrom, System.Text.Encoding.UTF8);
msg.Subject = strSubjet;

// msg.SubjectEncoding = System.Text.Encoding.UTF8;

msg.Body = strMsg;
// msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.High;

//Add the Creddentials
SmtpClient client = new SmtpClient();

client.Credentials = new System.Net.NetworkCredential("Game_XXX@xxxx.com",
"XXXX");

client.Port = 25;//or use 587
client.Host = "SMTP Mail Server Name";

// client.EnableSsl = true;
client.SendCompleted += new
SendCompletedEventHandler(client_SendCompleted);
object userState = msg;

try
{
//you can also call client.Send(msg)
client.SendAsync(msg, userState);
}

catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show(ex.Message, "Send Mail Error");
}

}
void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MailMessage mail = (MailMessage)e.UserState;
string subject = mail.Subject;

if (e.Cancelled)
{
string cancelled =
string.Format("[{0}] Send canceled.", subject);
MessageBox.Show(cancelled);
}

if (e.Error != null)
{
string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
MessageBox.Show(error);
}

else
{
MessageBox.Show("Message sent.");
t_from.Text = "";
t_to.Text = "";
t_subject.Text = "";
t_msg.Text = "";
t_mobile.Text = "";
}
mailSent = true;
}

private void button1_Click(object sender, EventArgs e)
{
this.SendMail();
mycon.Close();
}

}

}

0 comments: