I have never done the function of sending emails before. I needed it for a project some time ago. After looking for many posts, I finally realized it.
After that, I sorted it out and wrote a class. Pass information directly to the class and it can be sent.
It should also be noted here that sending emails requires opening the POP3/SMTP service, otherwise QQ mailboxes, NetEase mailboxes, etc. will report errors. There is no need to activate the receiving email address. You can find out how to activate it on Baidu.
public static class EmailHelper { /// <summary> /// 发送邮件 /// </summary> /// <param name="subject">邮件主题</param> /// <param name="msg">邮件内容</param> /// <param name="filePath">附件地址,如果不添加附件传null或""</param> /// <param name="senderEmail">发送人邮箱地址</param> /// <param name="senderPwd">发送人邮箱密码</param> /// <param name="recipientEmail">接收人邮箱</param> public static void SendMail(string subject, string msg, string filePath, string senderEmail, string senderPwd, params string[] recipientEmail) { if (!CheckIsNotEmptyOrNull(subject, msg, senderEmail, senderPwd) || recipientEmail == null || recipientEmail.Length == 0) { throw new Exception("输入信息无效"); } try { string[] sendFromUser = senderEmail.Split('@'); //构造一个Email的Message对象 MailMessage message = new MailMessage(); //确定smtp服务器地址。实例化一个Smtp客户端 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp." + sendFromUser[1]); //构造发件人地址对象 message.From = new MailAddress(senderEmail, sendFromUser[0], Encoding.UTF8); //构造收件人地址对象 foreach (string userName in recipientEmail) { message.To.Add(new MailAddress(userName, userName.Split('@')[0], Encoding.UTF8)); } if (!string.IsNullOrEmpty(filePath)) { Attachment attach = new Attachment(filePath); //得到文件的信息 ContentDisposition disposition = attach.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(filePath); disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath); disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath); //向邮件添加附件 message.Attachments.Add(attach); } //添加邮件主题和内容 message.Subject = subject; message.SubjectEncoding = Encoding.UTF8; message.Body = msg; message.BodyEncoding = Encoding.UTF8; //设置邮件的信息 client.DeliveryMethod = SmtpDeliveryMethod.Network; message.BodyEncoding = System.Text.Encoding.UTF8; message.IsBodyHtml = false; //如果服务器支持安全连接,则将安全连接设为true。 //gmail,qq支持,163不支持 switch (sendFromUser[1]) { case "gmail.com": case "qq.com": client.EnableSsl = true; break; default: client.EnableSsl = false; break; } //设置用户名和密码。 client.UseDefaultCredentials = false; //用户登陆信息 NetworkCredential myCredentials = new NetworkCredential(senderEmail, senderPwd); client.Credentials = myCredentials; //发送邮件 client.Send(message); } catch (Exception ex) { throw (ex); } } /// <summary> /// 验证所有传入字符串不能为空或null /// </summary> /// <param name="ps">参数列表</param> /// <returns>都不为空或null返回true,否则返回false</returns> public static bool CheckIsNotEmptyOrNull(params string[] ps) { if (ps != null) { foreach (string item in ps) { if (string.IsNullOrEmpty(item)) return false; } return true; } return false; } }
Call the method directly, pass the information that needs to be sent, and then you can send the email.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles related to C# sending email implementation code, please pay attention to the PHP Chinese website!

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.