Saturday, September 28, 2013

Mailing through c#

what we normally have to send a mail is create account and send mails through that account.but here i explains how to create interface to send mails using smtp server along with the attachments.it is clearly checking for network connection and empty streams of the fields in interface.therefore we can easily find which is the error by looking at message box.

this is the main implementation method which we can use.here i have passed 5 parameters as receiver mail address,message body,subject, attachment 1 and attachment 2.This is the purpose of i want only 2 attachments.If you want more than 2 attachments you can pass another parameter.
here in locations which i mentioned as "your mail address" and "your password", you should enter your mail account details.since this is using smtp server.it should be gmail account.
if the credentials have been successfully submitted message will sent successfully.



 public void mail(string receiver,string msg,string subject,string attachment1,string attachment2)
        {
            try
            {

                System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(<your mail address>, receiver, subject, msg + " < CECB Experiments Results Updates >");

                MyMailMessage.IsBodyHtml = false;

                System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(<give your  mail address>,<give your mail password>);

                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

                string file = attachment1;
                string file2 = attachment2;
                Attachment attach = new Attachment(file);
                Attachment attach2 = new Attachment(file2);

                // Add the file attachment to this e-mail message.


                MyMailMessage.Attachments.Add(attach);
                MyMailMessage.Attachments.Add(attach2);

                mailClient.EnableSsl = true;
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = mailAuthentication;
                mailClient.Send(MyMailMessage);
                MessageBox.Show("Mail sent success!");

            }


            catch (Exception ee)
            {
                MessageBox.Show("Receiver's Mail , Attachment can't be Empty..Please Check", "Invalid or Empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
           
            }



Then in necessary places we can call the method by passing parameters.









No comments:

Post a Comment