C#实现发送和接受邮件的winform邮箱
一、C#邮箱总体介绍
初学C#,使用DevExpress做了个WInform的邮箱,邮箱的主界面如下所示:
主要完成的功能有
- 邮箱客户端的登入功能,用户的邮箱和密码存储在MySQL的数据库之中,只有和数据库中信息匹配才允许登入。
- 邮件的发送和接收功能。
- 把用户接收的邮件存储在数据库之中,并使用GridControl进行展示。
- 设置CN/EN语言
二、C#本地邮箱如何实现
1. 登入界面
主要登入界面如上图所示,点击sign in 之后可登入至主界面。
登入界面的UI实现很简单,就是直接从DevExpress里拖动控件完成。
具体的逻辑实现如下:
namespace Mailclient_demo1
{
public partial class login : DevExpress.XtraEditors.XtraForm
{
// DBConnect is completed by me
DBConnect DBConnect1 = new DBConnect();
public static String emailaddress, password;
public login()
{
InitializeComponent();
}
private void Btn_Register_Click(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.None;//无边框
}
//点击登入按钮
private void button1_Click(object sender, EventArgs e)
{
emailaddress = textBox_email_address.Text;
password = textBox_password.Text;
//Test if the emailaddress and password is in the database
if (DBConnect1.check(emailaddress, password) == true)
{
this.Hide();
//show main
Mainform Mf = new Mainform();
Mf.ShowDialog();
}
else
{
MessageBox.Show("sad...login unsuccessfully");
}
}
}
}
首先需要在数据库中保存已有的email address 和 password的信息:
然后和数据库连接:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Add MySql Library
using MySql.Data.MySqlClient;
namespace Mailclient_demo1
{
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "emailclient";
uid = "root";
password = "Zhu19971125123!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Search if the emailaddress and password is in the database
public bool check(string emailaddress, string password)
{
String sql = "select Email_address,Password from login_email where Email_address='" + emailaddress + "'and Password='" + password + "'";
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader sqlDataReader = cmd.ExecuteReader();
if (sqlDataReader.HasRows)
{
connection.Close();
this.CloseConnection();
return true;
}
else
{
connection.Close();
this.CloseConnection();
return false;
}
}
return false;
}
}
}
2. 发送邮件
发送邮件的UI也很简单,拖动控件就好。
首先得使用SMTP来发送邮件,具体见代码
using System.Net;
using System.Net.Mail;
//Test send email
namespace Mailclient_demo1
{
class Class1
{
public string sendsuc = "Send successfully";
public string smtpAddress = "smtp-mail.outlook.com";
public int portNumber = 587;
public bool enableSSL = true;
public string emailFromAddress = "Sender Email Address "; //Sender Email Address
public string password = "Sender Password"; //Sender Password
public string emailToAddress = "Receiver Email Address "; //Receiver Email Address
public string subject = "Hello";
public string body = "Hello, This is Email sending test using gmail.";
public string attachment ="";
//Use Smtp to send email
public void SendEmail()
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFromAddress);
mail.To.Add(emailToAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
//--Uncomment this to send any attachment
if (attachment != "")
{
mail.Attachments.Add(new Attachment(attachment));
}
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
}
}
接下来写逻辑来调用send email
namespace Mailclient_demo1
{
public partial class SendClient : DevExpress.XtraEditors.XtraForm
{
//全局的 c1 means send email function c1
Class1 c1 = new Class1();
public SendClient()
{
InitializeComponent();
//Obtain the basic inforamtion
}
private void btn_sendmail_Click(object sender, EventArgs e)
{
//send
c1.emailToAddress = textBox_To.Text;
c1.subject = textBox_Subject.Text;
c1.body = textBox_Body.Text;
c1.SendEmail();
MessageBox.Show(c1.sendsuc);
}
//add attachments
private void btn_attach_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "choose the document";
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
c1.attachment = dialog.FileName;
label_attach.Text = dialog.FileName;
}
}
}
}
3. 接收邮件
Imap接收邮件
接收邮件会比较复杂,因为C#中没有自带的Imap库,所以需要在NuGet中下载EAGetMail这个库。
然后用MailServer来接收邮件
namespace Mailclient_demo1
{
class Reveivemailclass
{
public string show_receviemial_num(string emailaddress, string password)
{
string output = "";
try
{
MailServer oServer = new MailServer("outlook.office365.com",
emailaddress,
password,
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
output = infos.Length.ToString();
for (int i = 0; i < infos.Length; i++)
{
string line = "";
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
line = line + ("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL) + "\r\n";
// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
//form
Console.WriteLine("From: {0}", oMail.From.ToString());
line = line + ("From: ", oMail.From.ToString()) + "\r\n";
//to
Console.WriteLine("To[0]: {0}", oMail.To[0].ToString());
line = line + ("To", oMail.To[0].ToString()) + "\r\n";
Console.WriteLine("ReceivedDate: {0}", oMail.ReceivedDate.ToString());
line = line + ("ReceivedDate: ", oMail.ReceivedDate.ToString()) + "\r\n";
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
line = line + ("Subject: ", oMail.Subject) + "\r\n";
Console.WriteLine("TextBody: {0}\r\n", oMail.TextBody);
line = line + "TextBody: " + oMail.TextBody + "\r\n";
line = line + "\r\n";
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
return output;
}
接收邮件并保存到MySQL数据库之中
public void save_receivemail(String emailaddress, string password)
{
string output = "";
MailServer oServer = new MailServer("outlook.office365.com",
emailaddress,
password,
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
String sender, recipient, subject, body;
output = output + "Total " + infos.Length + "email(s)\r\n";
//Open database
MySqlConnection connectionre;
string connectionString;
connectionString = "SERVER=" + "localhost" + ";" + "DATABASE=" +
"emailclient" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "Zhu19971125123!" + ";";
connectionre = new MySqlConnection(connectionString);
connectionre.Open();
//Display no more than 20
int lengthinfo = infos.Length;
if (lengthinfo >= 20)
{
lengthinfo = 20;
}
//save
for (int i = 0; i < lengthinfo; i++)
{
MailInfo info = infos[i];
// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
//把"fangzheng zhu" <fangzheng.zhu@tradex.com.sg> 变成 <fangzheng.zhu@tradex.com.sg>
String sender_ori = oMail.From.ToString();
string[] sArray = sender_ori.Split(new char[2] { '<', '>' });
sender = "<" + sArray[1] + ">";
String recipient_ori = oMail.To[0].ToString();
string[] rArray = recipient_ori.Split(new char[2] { '<', '>' });
recipient = "<" + rArray[1] + ">";
subject = oMail.Subject.ToString();
subject=subject.Substring(0, subject.Length - 16);
body = oMail.TextBody.ToString();
//check if is already in the database
//save to database
/*String sqlsave = "if not exists(select count(*) from receive_email " +
"where Sender = '"+ oMail.From.ToString() + "' and Recipient = '"+ oMail.To[0].ToString()+ "' and Subject = '"+ subject+"')" +
"INSERT INTO receive_email(Sender,Recipient,Subject) " +
"VALUES('" + oMail.From.ToString() + "','" + oMail.To[0].ToString() + "','" + subject + "')";*/
/*String sqlsave = "if not exists(select count(*) from receive_email " +"')" +
"INSERT INTO receive_email(Sender,Recipient,Subject) " +
"VALUES('" + oMail.From.ToString() + "','" + oMail.To[0].ToString() + "','" + subject + "')";*/
//IGNORE
String sqlsave = "INSERT IGNORE INTO receive_email(Sender,Recipient,Subject,Body) " +
"VALUES('" + sender + "','" + recipient + "','" + subject + "','"+ body + "')";
MySqlCommand cmdsave = new MySqlCommand(sqlsave, connectionre);
cmdsave.ExecuteNonQuery();
}
connectionre.Close();
oClient.Quit();
Console.WriteLine("Completed!");
}
与前端UI组合逻辑
用到了GridControl这个控件
namespace Mailclient_demo1.UI
{
public partial class receive_emai_form : DevExpress.XtraEditors.XtraForm
{
Reveivemailclass rm = new Reveivemailclass();
MySqlConnection connection;
public receive_emai_form()
{
InitializeComponent();
}
public void conopen()
{
string connectionString;
connectionString = "SERVER=" + "localhost" + ";" + "DATABASE=" +
"emailclient" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "Zhu19971125123!" + ";";
connection = new MySqlConnection(connectionString);
connection.Open();
}
public MySqlDataReader getinfo()
{
conopen();
//确保Recipient正确
String sql = "select Sender,Recipient,Subject from receive_email where Recipient = '<" + login.emailaddress + ">'" ;
//"VALUES('" + oMail.From.ToString() + "','" + oMail.To[0].ToString() + "','" + subject + "')";
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader data = cmd.ExecuteReader();
return data;
}
private void receive_emai_form_Load(object sender, EventArgs e)
{
this.GridControl.DataSource = getinfo();
connection.Close();
Label_totalemail2.Text = rm.show_receviemial_num(login.emailaddress, login.password);
Label_unreademail2.Text = rm.show_newreceviemial_num(login.emailaddress, login.password);
}
//renew
private void simpleButton2_Click(object sender, EventArgs e)
{
Label_totalemail2.Text = rm.show_receviemial_num(login.emailaddress, login.password);
Label_unreademail2.Text = rm.show_newreceviemial_num(login.emailaddress, login.password);
rm.save_receivemail(login.emailaddress, login.password);
this.GridControl.DataSource = getinfo();
connection.Close();
}
private void Label_totalemail_Click(object sender, EventArgs e)
{
}
private void simpleButton1_Click(object sender, EventArgs e)
{
//show sendclient
SendClient Sc = new SendClient();
Sc.ShowDialog();
}
private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
XtraMessageBox.Show(gridView1.GetFocusedRow().ToString());
}
private void repositoryItemButtonEdit4_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
//事件中获取行对象核心代码:
int rowIndex = gridView1.FocusedRowHandle;
//XtraMessageBox.Show(gridView1.GetRowCellDisplayText(rowIndex, "Subject").ToString());
Content_form CF = new Content_form();
String sender1= gridView1.GetRowCellDisplayText(rowIndex, "Sender").ToString();
String recipient1 = gridView1.GetRowCellDisplayText(rowIndex, "Recipient").ToString();
String subject = gridView1.GetRowCellDisplayText(rowIndex, "Subject").ToString();
CF.labelControl_s.Text = "sender: " + sender1;
CF.labelControl_r.Text = "recipient: " + recipient1;
CF.labelControl_subject.Text = "Subject: " + subject;
//Open database
conopen();
String sqll = "select Body from receive_email where Sender='" + sender1 + "'and Recipient='" + recipient1 + "' and Subject='"+ subject +"'";
MySqlCommand cmd = new MySqlCommand(sqll, connection);
MySqlDataReader sqlDataReader = cmd.ExecuteReader();
// need to read first then get the information. Fangzheng
sqlDataReader.Read();
String Body = sqlDataReader["Body"].ToString();
if (sqlDataReader.HasRows)
{
CF.textBox_receive.Text = "Body: \r\n" + Body;
connection.Close();
}
else
{
connection.Close();
}
CF.ShowDialog();
}
}
}