Showing posts with label Sending Emails. Show all posts
Showing posts with label Sending Emails. Show all posts

Friday, May 22, 2009

How To: Sending Email Using C#

in this article I'll show you how can you send mail using windows application
I'm using gmail becouse it allowed sending and recieving Emails and you need to make some configurations like:
Host Name: smtp.gmail.com
Port Number: 587
Your Email Address: yourEmail@gamil.com
your Password: your Email Password
SSL:true (becouse gmail using ssl)

Let's start...

Create Windows Application using C# :
Create Form Like the Below Form with Controls

Important Note Controls Names Will be Like:

textbox =txt...
label=lbl...
button=btn...




using System.Net;
using System.Net.Mail;


then create some properities :
you can put them in seperated class but I'm putted them in the same form because it's a sample

public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailBody { get; set; }
public string MailSubject { get; set; }
public string AttachmentFile { get; set; }
public string HostName { get; set; }
public int PortNumber { get; set; }
public string EmailAddress { get; set; }
public string EmailPassword { get; set; }
public bool SSL { get; set; }


then create method for sending mail:

public void SendingMail()
{
MailMessage mailMessage = new MailMessage(MailFrom,MailTo,MailSubject,MailBody);
Attachment fileAttachment = new Attachment(AttachmentFile);
mailMessage.Attachments.Add(fileAttachment);
SmtpClient smtpClient = new SmtpClient(HostName,PortNumber);
smtpClient.Credentials = new NetworkCredential(EmailAddress,EmailPassword);
smtpClient.EnableSsl = SSL;
smtpClient.Send(mailMessage);
}


in attachment button put the following code:

private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
lblAttachment.Text = fileDialog.FileName;
}


in Send Mail Button put the following code:

private void btnSendMail_Click(object sender, EventArgs e)
{
try
{
MailFrom = txtMailAddress.Text; ;
MailTo = txtTo.Text;
MailBody = txtBody.Text;
MailSubject = txtSubject.Text;
AttachmentFile = lblAttachment.Text;
HostName = txtHostName.Text;
PortNumber = Convert.ToInt16(txtPortNo.Text);
EmailAddress = txtMailAddress.Text;
EmailPassword = txtMailPassword.Text;
SSL = chkSSL.Checked;
SendingMail();
MessageBox.Show("Sending Mail Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}