Wednesday, September 7, 2011

C# code for send Email

The below sample code showing how to send an email in asp.net


using System.Net.Mail;

string strFromAdd = "sample@gmail.com";
string strFromAddPass = "123456789";
string strSubject = "Subject Text";
string mailstring ="Mail Content";
string strAttachmentPath = Server.MapPath("..\\file\\sample.pdf");
MailMessage mail = new MailMessage();
mail.To.Add(strToAdd);
mail.From = new MailAddress(strFromAdd);
mail.Subject = strSubject;
mail.BodyEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailstring, @"%&$^/<(.|\n)*?>", string.Empty), null, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailstring, null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
mail.Attachments.Add(new Attachment(strAttachmentPath));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Port = 587;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(strFromAdd, strFromAddPass);
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

C# code for upload image file into database

Database Table

Fields
                          Type
img_name                - varchar(50)
img_data                  - image
img_contenttype       -varchar(50)

In Web form


1.    Add fileupload control
2.    Add button control
3.    Add label control for message display
4.    Write the below code in button onclick event

C# Code
Stream imgstream = FileUpload1.PostedFile.InputStream;
int imglen = FileUpload1.PostedFile.ContentLength;
string imgname = FileUpload1.FileName;
string imgtype = FileUpload1.PostedFile.ContentType;
//create a byte array
byte[] imgdata = new byte[imglen];
//convert Image Stream to a Byte array
int n = imgstream.Read(imgdata, 0, imglen);

SqlConnection scon = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);

(Or)
SqlConnection scon = new SqlConnection("ConnectionString");
string Sql = "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( '" + imgname + "', '" + imgdata + "','" + imgtype + "' )";
SqlCommand cmd = new SqlCommand(Sql, scon);
scon.Open();
int val = cmd.ExecuteNonQuery();
scon.Close();
if (val > 0)
{
Label1.Text = "The Image was saved";
}
else
{
Label1.Text = "An error occurred uploading the image";       
}