This snippet demonstrates how to send mail via Smtp with .NET 2.0.
For that it uses the MailMessage-and SmtpClient-class.
The programm attached is a simple SendMail Console-Client.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
namespace SmtpMail
{
class Program
{
///
/// Console App to send mails via Smtp
///
/// From
/// To
/// Subject
/// Body
/// Host
/// Port
/// User
/// Password
static void Main(string[] args)
{
try
{
// TODO: Add error handling for invalid arguments
// To
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add(args[1]);
// From
MailAddress mailAddress = new MailAddress(args[0]);
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = args[2];
mailMsg.Body = args[3];
// Init SmtpClient and send
SmtpClient smtpClient = new SmtpClient(args[4], Convert.ToInt32(args[5]));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(args[6], args[7]);
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine( ex.Message );
}
}
}
}
===================================================================================
Send Email in C# Code
In order to send email in C# code, do the following:
// create mail message object
MailMessage mail = new MailMessage();
mail.From = ""; // put the from address here
mail.To = ""; // put to address here
mail.Subject = ""; // put subject here
mail.Body = ""; // put body of email here
SmtpMail.SmtpServer = ""; // put smtp server you will use here
// and then send the mail
SmtpMail.Send(mail);
=========================================================================================
public void Send() {
MailMessage MailMesaji = new MailMessage();
MailMesaji.Subject = "subject";
MailMesaji.Body = "mail body";
MailMesaji.BodyEncoding = Encoding.GetEncoding("Windows-1251"); // Cyrillic Character Encoding
MailMesaji.From = "sender mail adress";
this.MailMesaji.To.Add(new MailAddress("to mail adress"));
System.Net.Mail.SmtpClient Smtp = new SmtpClient();
Smtp.Host = "smtp.gmail.com"; // for example gmail smtp server
Smtp.EnableSsl = true;
Smtp.Credentials = new System.Net.NetworkCredential("account name", "password");
Smtp.Send(MailMesaji);
}