介绍下mailmessage如何使用
时间: 2024-04-22 07:24:38 浏览: 18
`MailMessage` 是 .NET Framework 中的一个类,用于创建和操作电子邮件消息。它位于 `System.Net.Mail` 命名空间中。下面是一个简单的示例代码,演示如何使用 `MailMessage` 发送电子邮件:
```csharp
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main()
{
// 创建一个 MailMessage 实例
MailMessage message = new MailMessage();
// 设置发件人地址
message.From = new MailAddress("sender@example.com");
// 设置收件人地址
message.To.Add("recipient@example.com");
// 设置邮件主题和正文
message.Subject = "Hello, World!";
message.Body = "This is the content of the email.";
// 创建一个 SmtpClient 实例,并配置发送邮件的 SMTP 服务器信息
SmtpClient smtpClient = new SmtpClient("smtp.example.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential("username", "password");
try
{
// 发送邮件
smtpClient.Send(message);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
```
在上述示例中,你需要将发件人和收件人的电子邮件地址替换为实际的地址。同时,你还需要提供用于发送邮件的 SMTP 服务器的主机名、端口号、用户名和密码。
这只是一个基本示例,你可以根据具体需求进一步自定义邮件的内容和设置。希望对你有所帮助!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)