How to Send an Email using C#.NET?
You see, When you create a desktop application, you need to build such a system which can send email. This is crucial because when the user register into your system, you need to get notified and it is also useful in case such as when your client forget their password, they can send request for the password through your system. This overcome the problem of opening browser and login to any email provider website and send email to you for their password.
Steps:
[sociallocker]
I am assuming that you have Visual Studio, Open your Visual Studio and click on File>new project, From the left side of your window, select Visual C#>Window and from the middle side select Windows Forms Application and then give the name of your project and then click OK which is shown in below.
2. From the ToolBox Drag and Drop four label, four Textbox and one button in your form and change the properties of these controls by selecting each control and right click that particular control and click on properties.(You can change the color of each control, increase the font of each control)
Four Label for Receiving email, sending email, password of sending email, Actual Mail Message
Four Textbox for Receiving email, sending email, password of sending email, Actual Mail Message
Button to send
NOTE: You can increase the message box large for this select message box textbox go to properties and then change the multiline to true and ScrollBars to Both and the expand this textbox by dragging it. And change the password Text Box property PasswordChar to any character so that you can hide your password.
3. Double click on Send button to go to the .cs section of your project and scroll up and then add the following namespace to your program as:
using System.Net; using System.Net.Mail;
4. Write the following piece of code inside the clicking event of Login Button:
string to, from, pass, mail; to = (txtReceiver.Text).ToString(); from = (txtSender.Text).ToString(); mail = (txtMail.Text).ToString(); pass = (txtPassword.Text).ToString(); MailMessage message = new MailMessage(); message.To.Add(to); message.From = new MailAddress(from); message.Body = mail; message.Subject = "Email Testing"; SmtpClient smtp = new SmtpClient("smtp.gmail.com"); smtp.EnableSsl = true; smtp.Port = 587; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(from, pass); try { smtp.Send(message); MessageBox.Show("Email send successfully", "Email", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message); }
5. Run your project by clicking in that play button. Input your credentials of gmail enter the phone number in which you want to send SMS and type your Message in respective textbox and then click on Send button. That’s it.
[/sociallocker]
if you have any confusion, you can watch the following video: