search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of the code to implement email sending in .NET

This article mainly introduces the method of sending emails in ASP.NET Core in detail and tells you how to send emails in ASP.NET Core. It has certain reference value. Interested friends can refer to it

Preface

We know that currently .NET Core does not support the SMTP protocol. When we use the function of sending emails, we need to use some third-party components to achieve it. Purpose, today I will introduce to you two open source email sending components, namely MailKit and FluentEmail. I will introduce them respectively below.

MailKit

In ASP.NET Core, you can use MailKit to send emails. It supports cross-platform and supports IMAP, POP3, SMTP and other protocols.

You can use the following methodInstallation:

Install-Package MailKit

The following is a simple Example of sending an email:

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com"));

message.Subject = "星期天去哪里玩?";

message.Body = new TextPart ("plain") { Text = "我想去故宫玩,如何" };

using (var client = new SmtpClient ()) {
 // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
 client.ServerCertificateValidationCallback = (s,c,h,e) => true;

 client.Connect ("smtp.friends.com", 587, false);

 // Note: since we don't have an OAuth2 token, disable
 // the XOAUTH2 authentication mechanism.
 client.AuthenticationMechanisms.Remove ("XOAUTH2");

 // Note: only needed if the SMTP server requires authentication
 client.Authenticate ("joey", "password");

 client.Send (message);
 client.Disconnect (true);
}

If the Body content you want to send is HTML, you can use the following:

var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = @"<b>This is bold and this is <i>italic</i></b>";
message.Body = bodyBuilder.ToMessageBody();

Fluent Email

Fluent Email is also an open source project. With it, you can use the Razor template to send emails, and you can integrate some third-party email sending programs such as Mailgun, etc., but this package is only available under .NET 4.6 Only supports SMTP. You can use the following command to install it:

Install-Package FluentEmail.Razor

You can use the most basic way to send emails, it is as simple as the following :

//注意: .NET 4.6 才支持
Email.DefaultSender = new SmtpSender();

var email = Email
 .From("foo@email.com")
 .To("bar@email.com", "bob")
 .Subject("星期天去哪里玩?")
 .Body("我想去故宫玩,如何?");

await email.SendAsync();

Alternatively, you can use the Razor template to send:

//注意: .NET 4.6 才支持
Email.DefaultSender = new SmtpSender();

// Using Razor templating package
Email.DefaultRenderer = new RazorRenderer();

var template = "Dear @Model.Name, You are totally @Model.Compliment.";

var email = Email
 .From("bob@hotmail.com")
 .To("somedude@gmail.com")
 .Subject("woo nuget")
 .UsingTemplate(template, new { Name = "Luke", Compliment = "Awesome" });

Email.DefaultRenderer tells FulentEmail which renderer to use (you also You can implement your own), and then provide a template template whose content is Razor syntax template string , and then use UsingTemplate for rendering.

cshtml template on disk

Add to your email Razor template file is relatively large, and it is not elegant to express it with a string, then you can put the template file in to the disk, and then load it using the following method:

//注意: .NET 4.6 才支持
Email.DefaultSender = new SmtpSender();

Email.DefaultRenderer = new RazorRenderer();

var email = Email
 .From("foo@email.com")
 .To("bar@email.com", "bob")
 .Subject("星期天去哪里玩?")
 .UsingTemplateFromFile($"{Directory.GetCurrentDirectory}/EmailTemplage.cshtml", new {Name ="Luke"})

Use Mailgun to send mail

There may be some people who are not clear about Mailgun. Mailgun is a foreign Email service companies, such as the famous Github email service, are hosted on it. The free Maingun account can send 10,000 emails per month, which is enough for many small and medium-sized websites.

When using Mailgun to send emails, you first need to register an account, and then you can use the Rest API provided by Mailgun to manage the emails sent or received. To use FluentEmail integrated Mailgun, you only need to add the following package:

Install-Package FluentEmail.Mailgun

After registering Mailgun, you will be assigned an API Key and a second-level domain name. In the program, you need the following configuration:

// 同时支持 .NET Core 和 .NET Framework
var sender = new MailgunSender(
 "sandboxcf5f41bbf2f84f15a386c60e253b5fe8.mailgun.org", // Mailgun 二级域名
 "key-8d32c046d7f14ada8d5ba8253e3e30df" // Mailgun API Key
);

Email.DefaultSender = sender;

var email = Email
 .From("foo@email.com")
 .To("bar@email.com", "bob")
 .Subject("星期天去哪里玩?")
 .Body("我想去故宫玩,如何?");

await email.SendAsync();

Summary

Through the above example we can see that MailKit and FluentEmail Each has advantages and disadvantages. The advantage of MailKit is that it supports many protocols and is cross-platform, but the disadvantage is that it does not provide support for Razor, and if you use Mailgun, you need to integrate it yourself. The advantage of FlentEmail is that it provides support for Razor templates and encapsulates Mailgun. The disadvantage is that the SMTP protocol does not yet provide support for .NET Core.

To sum up, if you use Mailgun to send emails, then FluentEmail is the one you should choose. If you want to use the SMTP protocol to connect to your own mail server to send emails, then you should use MailKit .

【Related Recommendations】

1. ASP Free Video Tutorial

2. ASP Tutorial

3. Li Yanhui ASP basic video tutorial

The above is the detailed content of Detailed explanation of the code to implement email sending in .NET. For more information, please follow other related articles on the PHP Chinese website!

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
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

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

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

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.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

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

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

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# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

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 C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

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.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software