search
HomeBackend DevelopmentC#.Net TutorialC# Supplementary SmtpClient Class

SmtpClient Class

Allows applications to send email using Simple Mail Transfer Protocol (SMTP).

Namespace: system.net.mail

Properties

ClientCertificates: Specifies which certificate should be used to establish a Secure Sockets Layer (SSL) connection

Credentials: Gets or sets the credentials used to authenticate the sender

DeliveryFormat: Gets or sets the delivery format used by SmtpClient to send emails

DeliveryMethod: Specifies how to send emails Mail will handle the message

EnableSsl: Specifies whether SmtpClient uses Secure Socket Layer (SSL) encrypted connections

Host: Gets or sets the IP of the host used to record one or more SMTP transactions Address

PickupDirectoryLocation: Gets or sets the folder in which the application saves mail for processing by the local SMTP server

Port: Gets or sets the port used for SMTP transactions

ServicePoint: Gets the network connection used to transmit email

TargetName: Gets or sets the service provider name (SPN) when using extended protection for authentication

Timeout: Gets or sets A value that specifies the timeout for Send calls

UseDefaultCredentials: Gets or sets a Boolean value that controls whether DefaultCredentials are sent with the request

Method

Dispose()

Send a QUIT message to the SMTP server, terminate the TCP connection normally, and release all resources of the SmtpClient class used by the current instance

Dispose(Boolean)

Send a QUIT message When sent to the SMTP server and the TCP connection is terminated normally, all resources of the SmtpClient class used by the current instance are released, and managed resources can be released as needed

Equals(Object)

Determine the specified object Whether it is equal to the current object

Finalize()

Allows an object to try to release resources and perform other cleanup operations before the garbage collection mechanism will recycle it

GetHashCode()

As the default hash function

GetType()

Get the Type of the current instance

MemberwiseClone()

Create the current Object Shallow copy

OnSendCompleted(AsyncCompletedEventArgs)

Raises the SendComplete event

Send(MailMessage)

Sends the specified message to the SMTP server for delivery

Send(String, String, String, String)

Sends the specified email to the SMTP server for delivery. The email sender, recipient, subject, and message body are sent to the SMTP server for delivery using the specified String object

SendAsync(MailMessage, Object)

. This method does not block the calling thread and allows the caller to pass the object to the method that is called when the operation completes

SendAsync(String, String, String, String, Object)

Will send a The email is sent to the SMTP server for delivery. The email sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass the object to the method that is called when the operation completes.

SendAsyncCancel()

Cancel an asynchronous operation to send an email

SendMailAsync(MailMessage)

Sends the specified message to the SMTP server for an asynchronous operation transmitted in the form.

SendMailAsync(String, String, String, String)

Sends the specified message to the SMTP server for delivery as an asynchronous operation. . The email sender, recipients, subject, and message body are specified using String objects.

ToString()

Returns a string representing the current object. (Inherited from Object.)

Event

SendCompleted

Occurs when an asynchronous email send operation is completed

Remarks

Table below The class shown in is used to build emails that can be sent using the SmtpClient.

Attachment class

Represents a file attachment, this class allows you to attach a file, stream, or text to an email

MailAddress class

Represents a sending message The email address of the person and recipient

MailMessage class

Represents an email

To construct and send an email using SmtpClient, you must specify the following information :

The SMTP host server used to send emails.

For authentication, if SMTP server requires credentials.

Sender email address.

Email address or recipient's address.

Message content.

To include an attachment in an email, first create the attachment using the Attachment class, and then add it to the message via the MailMessage.Attachments property. Depending on the email reader used and the file type of the attachment, some recipients may not be able to read the attachment. For clients that cannot maintain attachments displayed in their original format, you can specify an alternate view by specifying the MailMessage.AlternateViews property.

You can use the application or computer configuration file to specify default host, port, and credential values ​​for all SmtpClient objects.

To send emails and chunks while waiting for the email to be transmitted to the SMTP server, use a synchronous Send method. To allow the program's main thread to continue executing while transmitting emails, use one of the asynchronous SendAsync methods. The SendCompleted event is raised when the SendAsync operation completes. To receive this event, you must add a SendCompletedEventHandler delegate to SendCompleted. The callback method that the SendCompletedEventHandler delegate must reference to handle the notification's SendCompleted event. To cancel asynchronous email transmission, use the SendAsyncCancel method.

Main code for the email sending interface:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;using System.Windows.Forms;
using System.IO;using System.Net;using System.Net.Mail;
namespace SendEmail{
public partial class Form3 : Form{
string severaddress;string mailuser;string userpwd;public 
Form3(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
Form6 form = new Form6();
form.SendParaHandler +=new Form6.SendPara(reload);
//事件的挂接form.Show();
}
public void reload(){
StreamReader read = new StreamReader(@"fajianren.asdf");
severaddress = read.ReadLine();
mailuser = read.ReadLine();
userpwd = read.ReadLine();
read.Close();}
private void Form3_Load(object sender, EventArgs e){
reload();}
public bool sendmail(string mailfrom,string mailto,string mailsubject,string mailbody){
MailAddress from = new MailAddress(mailfrom);
MailMessage message = new MailMessage();
try{message.From = from;
message.To.Add(mailto);
message.Subject = mailsubject;
message.Body = mailbody;
message.Priority = MailPriority.Normal;
SmtpClient smtp = new SmtpClient();
smtp.Host = severaddress;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(mailuser,userpwd);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch(Exception e){ 
return 
false;
}
return 
true;
}
private void button2_Click(object sender, EventArgs e){
string mailfrom = mailuser;
string mailto = textBox1.Text;
string mailsubject = textBox2.Text;
string mailbody = textBox3.Text;
if (sendmail(mailfrom, mailto, mailsubject, mailbody)){
MessageBox.Show("邮件发送成功");
}
else{
MessageBox.Show("邮件发送失败");
}
}
}
}

Main code for setting the sender information interface:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SendEmail
{
public partial class Form
6 : Form
{public Form6(){InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
Write();
}
//加载信息
private void Form6_Load(object sender, EventArgs e){
StreamReader read = new StreamReader(@"fajianren.asdf");
textBox1.Text = read.ReadLine();
textBox2.Text = read.ReadLine();
textBox3.Text = read.ReadLine();
read.Close();
}
//写入信息
public void Write(){
StreamWriter write = new StreamWriter(@"fajianren.asdf");
write.WriteLine(textBox1.Text);
write.WriteLine(textBox2.Text);
write.WriteLine(textBox3.Text);
write.Close();
}
public delegate void SendPara();
//定义委托
public event SendPara SendParaHandler;
//定义事件
private void button2_Click(object sender, EventArgs e){
SendParaHandler.Invoke();
Write();
this.Close();
}
}
}

The above is the content of the SmtpClient class in C#. For more related information, please Follow the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft