C# 发送邮件
Max Zhang Lv4

C# 发送邮件

我们经常需要在 C# 中发送邮件,来通知用户或者发送报表等。以下是一种简单的实现方式。

使用 SmtpClient 类发送邮件

使用 SmtpClient 类来发送邮件,以下是一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Net;
using System.Net.Mail;

class Program
{
static void Main(string[] args)
{
// 设置发件人和收件人
string from = "src@example.com";
string to = "target@example.com";
MailAddress sendAddress = new MailAddress(from);
MailAddress receiveAddress = new MailAddress(to);

// 创建邮件消息
MailMessage message = new MailMessage(from, to)
{
Subject = "Test Email",
Body = "This is a test email from C#."
};
message.Subject = "Test Email";
message.Body = "This is a test email from C#.";

// 创建 SmtpClient 实例并设置 SMTP 服务器地址和端口号
string smtpService = "smtp.gmail.com";
SmtpClient smtpClient = new SmtpClient
{
Host = smtpService
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;

// 启用 SSL 加密(如果 SMTP 服务器要求安全连接)
smtpClient.EnableSsl = true;

// 设置凭据(如果 SMTP 服务器需要身份验证)
smtpClient.Credentials = new NetworkCredential("your_username", "your_password");

try
{
// 发送邮件
smtpClient.Send(message);
Console.WriteLine("Mail Send successfully");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send email: {ex.Message}");
}
finally
{
// 清理资源
smtpClient.Dispose();
message.Dispose();
}
}
}

邮件内容支持 HTML 格式

邮件内容支持 HTML 格式,可以通过设置 IsBodyHtml 属性来指定邮件内容是否为 HTML 格式。

1
2
3
4
5
6
7
MailMessage message = new MailMessage(from, to)
{
Subject = "Test Email",
Body = "<h1>This is a test email from C#.</h1>",
// 设置邮件内容为 HTML 格式
IsBodyHtml = true
};

这样邮件内容就可以支持 HTML 格式的排版了。

 评论
评论插件加载失败
正在加载评论插件