Very early on, I was just learning C #, but I really wanted to use C # to send my own emails. However, I have never found any suitable code on the Internet, A few of my friends were programming Socket, a LAN office management software, and I followed it, mainly implementing LAN chat, file transmission, video and audio chat, and other functions, at this time, I suddenly wanted to write a software for sending emails. No way. I had to study at 1.1 again. After checking MSDN several times, I was able to implement it and it was quite useful. So I took it out and shared it with my friends, if it is not clear enough, you will have to include it. If it is helpful to you, you can try it out... Now, let's get started!
Create a Windows application and design the interface as follows:
Figure 1. Programming Interface
The following describes the interface controls one by one:
1. In the groupbox of the sender information, a drop-down list is used to select the SMTP server. The SMTP server provides the server for sending emails. If you are using the 163 mailbox, the SMTP server is smtp.163.com. If it is Gmail, the SMTP server is smpt.gmail.com. The user name is the name of your login to this mailbox, for example, I have a gmail account youring2@gmail.com, then here you should fill in youring2. The name to be displayed is the name that the email recipient can see. You can enter it as needed. For example, if I want the recipient to know that the email is from Qi Fei, I will enter Qi Fei here, this is an optional option and can be left empty. Your mailbox password is your mailbox password. If it is 123, you enter 123. If it is 456, you enter 456. I will not disclose my mailbox password here.
2. In the groupbox of the recipient information, the recipient's name is the name of the person who wants to receive the email. You can enter or leave it blank. For example, if I wrote this email to youring2, I can enter youring2 here. Email is the recipient's address, if I want to send to youring2's 163 mailbox, I can fill in the youring2@163.com. This must be written, so I won't talk about it anymore...
3. In the mail information, the subject is followed by the attachment and content. Click Add to add an attachment, click Delete to delete the selected attachment, and click send to send the email.
If your interface design level is already very good, you can design an interface by yourself and directly design the code below!
You need to add the namespace: using System. Net. Mail;
Using System. Net. Mime;
Using System. Net;
Using System. IO;
Step 1: Add a Form Load event. The code of this event mainly implements form initialization. These codes can also be completed in the Form constructor.
Private void Form1_Load (object sender, EventArgs e)
{
// Add two smpt server names
CmbBoxSMTP. Items. Add ("smtp.163.com ");
CmbBoxSMTP. Items. Add ("smtp.gmail.com ");
// Set it to the drop-down list
CmbBoxSMTP. DropDownStyle = ComboBoxStyle. DropDownList;
// The first option is selected by default.
CmbBoxSMTP. SelectedIndex = 0;
// Add the content you want to initialize below, such as the display name and user name.
}
Step 2: Add a click event for the Add button. Used to select a file and add the file to the TreeView.
// Add button click event
Private void btnAdd_Click (object sender, EventArgs e)
{
// Define and initialize an OpenFileDialog Class Object
OpenFileDialog openFile = new OpenFileDialog ();
OpenFile. InitialDirectory = Application. StartupPath;
OpenFile. FileName = "";
OpenFile. RestoreDirectory = true;
OpenFile. Multiselect = false;
// Display the open file dialog box and determine whether the OK button is clicked.
If (openFile. ShowDialog () = DialogResult. OK)
{
// Obtain the selected file name
String fileName = openFile. FileName;
// Add the file name to the TreeView
TreeViewFileList. Nodes. Add (fileName );
}
}
Step 3: Add a click event of the delete button to delete the selected TreeView.
// Click the event of the delete button
Private void btnDelete_Click (object sender, EventArgs e)
{
// Determine whether a node is selected
If (treeViewFileList. SelectedNode! = Null)
{
// Obtain the selected node
TreeNode tempNode = treeViewFileList. SelectedNode;
// Delete the selected node
TreeViewFileList. Nodes. Remove (tempNode );
}
Else
{
MessageBox. Show ("select the attachment to be deleted. ");
}
}
Step 4 is also the most critical step. The Click Event of the "send" button is used to send emails.
// Send button click event
Private void btnSend_Click (object sender, EventArgs e)
{
Try
{
// Confirm the smtp server address. Instantiate an Smtp client
System. Net. Mail. SmtpClient client = new System. Net. Mail. SmtpClient (cmbBoxSMTP. Text );
// Generate a sending Address
String strFrom = string. Empty;
If (cmbBoxSMTP. SelectedText = "smtp.163.com ")
StrFrom = txtUserName. Text + "@ 163.com ";
Else
StrFrom = txtUserName. Text + "@ gmail.com ";
// Construct a sender address object
MailAddress from = new MailAddress (strFrom, txtDisplayName. Text, Encoding. UTF8 );
// Construct a recipient address object
MailAddress to = new MailAddress (txtEmail. Text, txtToName. Text, Encoding. UTF8 );
// Construct an Email Message object
MailMessage message = new MailMessage (from, );
// Add an attachment to the message
Foreach (TreeNode treeNode in treeViewFileList. Nodes)
{
// Get the file name
String fileName = treeNode. Text;
// Determine whether a file exists
If (File. Exists (fileName ))
{
// Construct an attachment object
Attachment attach = new Attachment (fileName );
// Obtain the File Information
ContentDisposition disposition = attach. ContentDisposition;
Disposition. CreationDate = System. IO. File. GetCreationTime (fileName );
Disposition. ModificationDate = System. IO. File. GetLastWriteTime (fileName );
Disposition. ReadDate = System. IO. File. GetLastAccessTime (fileName );
// Add an attachment to the email
Message. Attachments. Add (attach );
}
Else
{
MessageBox. Show ("file" + fileName + "not found! ");
}
}
// Add the subject and content of the email
Message. Subject = txtSubject. Text;
Message. SubjectEncoding = Encoding. UTF8;
Message. Body = rtxtBody. Text;
Message. BodyEncoding = Encoding. UTF8;
// Set email information
Client. DeliveryMethod = SmtpDeliveryMethod. Network;
Message. BodyEncoding = System. Text. Encoding. UTF8;
Message. IsBodyHtml = false;
// If the server supports secure connections, set the Security connection to true.
// Gmail support, which is not supported by 163. If it is gmail, set it to true.
If (cmbBoxSMTP. SelectedText = "smpt.163.com ")
Client. EnableSsl = false;
Else
Client. EnableSsl = true;
// Set the user name and password.
// String userState = message. Subject;
Client. usedefacrecredentials = false;
String username = txtUserName. Text;
String passwd = txtPassword. Text;
// User login information
NetworkCredential myCredentials = new NetworkCredential (username, passwd );
Client. Credentials = myCredentials;
// Send an email
Client. Send (message );
// Prompt that the message is sent successfully
MessageBox. Show ("sent successfully! ");
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}
The following is my running result:
Figure 2. Send Email
Now open my Gmail mailbox and check if I have received the email. I did not believe it:
Figure 3. View emails in the inbox
You can see it. It's just that simple. Do it yourself! Note that the Send method is used to Send the mail. You can also use the SendAsync method to Send the mail. If asynchronous, you need to set a callback function to handle the post-sending tasks. I am lazy here! I have two examples. One is synchronous. The other is synchronous. If you need source code, click here to download SendEmail.rar. Thank you for coming to the end. Thank you!