Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
4.33/5 (5 votes)
See more:
C#
using System.Net;
using System.Net.Mail;
OpenFileDialog dlg = new OpenFileDialog();
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string filename = dlg.FileName;
 
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
 
                mail.From = new MailAddress("me@mydomain.com");
                mail.To.Add("u@urdomain.com");
                mail.Subject = filename;
                mail.Body = "Report";
                Attachment attachment = new Attachment(filename);
                mail.Attachments.Add(attachment);
 
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
                SmtpServer.EnableSsl = true;
 
                SmtpServer.Send(mail);
            }




These codes are working perfectly for me however I can send only plain text as Email. How to send an Email with formatting features like bold italics color change etc as in Yahoo Mail. Also I need a RichTextBox code for includng all such buttons.

pls help.
Posted
Comments
Member 8968685 28-Nov-12 6:53am    
this code is not working in my system.. i am getting some exception...
can anyone pls help me.. the exception i got is:
System.Net.Mail.SmtpException was unhandled
Message="Failure sending mail."
Source="System"
StackTrace:
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at sendemail.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\xrih\Documents\Visual Studio 2008\Projects\sendemail\sendemail\Form1.cs:line 65
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at sendemail.Program.Main() in C:\Users\xrih\Documents\Visual Studio 2008\Projects\sendemail\sendemail\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.WebException
Message="Unable to connect to the remote server"
Source="System"
StackTrace:
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
InnerException: System.Net.Sockets.SocketException
Message="No connection could be made because the target machine actively refused it 173.194.67.109:25"
Source="System"
ErrorCode=10061
NativeErrorCode=10061
StackTrace:
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
InnerException:

 
Share this answer
 
Comments
CHill60 28-Jul-14 10:59am    
You are also more than 2 years late
Rishabh Mayur 29-Jul-14 5:59am    
ohhh... yes ..you are right i didnt see the date of the post .. i just randomly given the answere link ....

Probabily it can also help to the other peoples who search regarding this topic.. :)
try
{

MailMessage Msg = new MailMessage();
Msg.From = new MailAddress(txtTo.Text);
Msg.To.Add("hussainahmedshamsi@hotmail.com");
Msg.Subject = txtSubject.Text;
Msg.Body = txtMessage.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("hshamsi.knysys@gmail.com", "Hussain_ahmed");
smtp.EnableSsl = true;
smtp.Send(Msg);

}

catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
 
Share this answer
 
Comments
CHill60 10-May-14 12:50pm    
You're more than two years late
 
Share this answer
 
Comments
CHill60 13-Nov-13 6:40am    
off topic
Arif Ansari Code 13-Nov-13 6:44am    
Ok Dear can you
Tell me what is requirment here
CHill60 13-Nov-13 8:27am    
My apologies - when I followed the link the first time I got a completely different site... a fault at my end. I've undone my downvote (I think)
See the Example here

http://forums.asp.net/t/971802.aspx[^]
 
Share this answer
 
Comments
Member 10665816 20-Mar-14 20:04pm    
Finally someone knows how to do it! Thanks.
Basically, you need multi-part e-mail; and one or more parts could be HTML. Or RTF, which I would not recommend. For the e-mail, the content type should be: Content-Type: multipart/alternative or multipart/mixed. For each part, the content type should be a valid MIME type, such as text/html.

Please see:
http://en.wikipedia.org/wiki/MIME[^],
http://en.wikipedia.org/wiki/HTML_email[^].

Sending e-mail in .NET:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx[^].

For more complex cases where one part can reference another part, such as image referenced in HTML, please see my recent answer:
Sending HTML attachment with images[^].

The source code in this article also shows how to compose multipart e-mail using C#.

Please also see this CodeProject article:
Sending an Email in C# with or without attachments: generic routine.[^].

—SA
 
Share this answer
 
v4
Comments
thatraja 4-Mar-12 5:20am    
5!
Sergey Alexandrovich Kryukov 4-Mar-12 5:25am    
Thank you, Raja.
--SA
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Mar-12 4:49am    
I hope, too. My 5.
--SA
thatraja 4-Mar-12 5:20am    
5!
Anuja Pawar Indore 5-Mar-12 1:07am    
My 5
Suresh Chand Saini 21-Dec-12 5:11am    
how to send mail code

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900