Hi here i want to explain you how to send mail with attachment using C# class with Gmail SMPT client.
we can use using System.Net.Mail; name space which contains list of class like SmtpClient,MailAddressCollection,MailMessage and Attachement used for sending mail in C# code.
public void sendMail()
{
SmtpClient _SmtpClient = new SmtpClient("smtp.gmail.com");
MailAddressCollection _MailAddressCollection = new MailAddressCollection();
MailMessage _message = new MailMessage();
_message.From = new MailAddress("muralikrishna.surap@gmail.com");
_message.Body = "Body of the mail";
_message.Subject = "Sending mail from c# Code";
_message.To.Add("muralikrishna.surap@gmail.com,1234@gmail.com");
Attachment data = new Attachment("D:\\Attachement.xls");
_message.Attachments.Add(data);
_SmtpClient.Port = 587;
_SmtpClient.Credentials = new System.Net.NetworkCredential("muralikrishna.surap@gmail.com", "*****");
_SmtpClient.EnableSsl = true;
_SmtpClient.Send(_message);
}
Window application:
using System;
using System.Windows.Forms; //new name space include
using System.Net.Mail; //for mail using this name space
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address@gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("you attachment file");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
Posted by:
T.saravanan
on: 11/26/2011
Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Murali & Biswarup Ghosh,
Kindly post your code inside the code tag.