在这个分步指南中,我们分享了如何使用 Aspose.Email for .NET 在 C# 中发送电子邮件。我们在此 C# 控制台应用程序中使用 Gmail SMTP 服务器发送电子邮件,但您可以在任何类型的 .NET 应用程序中使用任何 SMTP 服务器发送电子邮件。
在 C# 中发送电子邮件的步骤
- 从 NuGet 包管理器设置 Aspose.Email for .NET
- 包括以下命名空间:Aspose.Email、Aspose.Email.Clients 和 Aspose.Email.Clients.Smtp
- 使用 Aspose.Email.License 类申请许可证
- 使用 MailMessage 类创建新电子邮件
- 创建 SmtpClient 类的实例
- 设置 Gmail SMTP 客户端信息以发送电子邮件
- 使用 SmtpClient 类的 Send 方法发送 email
使用 C# 发送电子邮件的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
//Add Aspose.Email for .NET package reference | |
//Use following namespaces to convert OTG to PDF format | |
using Aspose.Email; | |
using Aspose.Email.Clients; | |
using Aspose.Email.Clients.Smtp; | |
namespace SendEmailUsingSMTPServer | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before sending email through Gmail SMTP | |
//using Aspose.Email for .NET | |
Aspose.Email.License AsposeEmailLicense = new Aspose.Email.License(); | |
AsposeEmailLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//create an instance of MailMessage | |
MailMessage EmailMessage = new MailMessage(); | |
//Set email message properties which you want to specify | |
EmailMessage.Subject = "How to Send Mail Using SMTP Server in C#"; | |
EmailMessage.To = "ReceiverEmail@EmailServer.com"; | |
EmailMessage.Body = "This is a test of sending email using SMTP in C#."; | |
//Initiate an instance of SmptpClient class | |
SmtpClient SMTPEmailClient = new SmtpClient(); | |
//Set SMTP client properties so the email message can get through the server | |
SMTPEmailClient.Host = "smtp.gmail.com"; | |
SMTPEmailClient.Username = "YourEmail@gmail.com"; | |
SMTPEmailClient.Password = "Your Gamil Password"; | |
SMTPEmailClient.Port = 587; | |
SMTPEmailClient.SecurityOptions = SecurityOptions.SSLExplicit; | |
//Finally send the email message using Gmail's SMTP client | |
SMTPEmailClient.Send(EmailMessage); | |
} | |
} | |
} |
在 C# 中使用 Gmail SMTP 发送电子邮件时的问题
您可能会遇到"SMTP 服务器需要安全连接或客户端未通过身份验证"之类的异常。这是因为 Gmail 认为您的应用程序安全性较低,因此可能不允许使用其 SMTP 服务器发送电子邮件。修复 Gmail SMTP 问题 allow access to less secure apps to send email。