Use C# to send mail using Google’s Gmail. If you’ve ever wanted to send email using your Gmail account then take a look.
using System.Net;
using System.Net.Mail;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Please Enter UserId: ");
string username = Console.ReadLine();
Console.WriteLine("Please Enter password ");
//Console.OutputEncoding = Encoding.Unicode;
string password = ReadPassword();
Class1 gmail = new Class1(username,password);
MailMessage msg = new MailMessage("From Address", "To Address");
msg.Subject = "This is test mails from .net Program";
msg.Body = "This is the test Email using system.net namespace within a .net program";
gmail.Send(msg);
}
public static string ReadPassword()
{
string password = "";
ConsoleKeyInfo info = Console.ReadKey(true);
while (info.Key != ConsoleKey.Enter)
{
if (info.Key != ConsoleKey.Backspace)
{
Console.Write("*");
password += info.KeyChar;
}
else if (info.Key == ConsoleKey.Backspace)
{
if (!string.IsNullOrEmpty(password))
{
// remove one character from the list of password characters
password = password.Substring(0, password.Length - 1);
// get the location of the cursor
int pos = Console.CursorLeft;
// move the cursor to the left by one character
Console.SetCursorPosition(pos - 1, Console.CursorTop);
// replace it with space
Console.Write(" ");
// move the cursor to the left by one character again
Console.SetCursorPosition(pos - 1, Console.CursorTop);
}
}
info = Console.ReadKey(true);
}
// add a new line because user pressed enter at the end of their password
Console.WriteLine();
return password;
}
}
public class Class1
{
public string Username { get; set; }
public string Password { get; set; }
public Class1(string username, string password)
{
Username = username;
Password = password;
}
public void Send(MailMessage msg)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(Username, Password);
client.Send(msg);
}
}
}