C#語言 如何寄Mail
时间: 2023-11-23 10:57:08 浏览: 32
以下是使用C#语言发送邮件的示例代码:
```csharp
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main(string[] args)
{
// 设置发件人邮箱地址、密码和SMTP服务器地址
string fromAddress = "your_email_address@example.com";
string password = "your_email_password";
string smtpServer = "smtp.example.com";
// 设置收件人邮箱地址
string toAddress = "recipient@example.com";
// 创建MailMessage对象
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
// 设置邮件主题和正文
mailMessage.Subject = "邮件主题";
mailMessage.Body = "邮件正文";
// 创建SmtpClient对象
SmtpClient smtpClient = new SmtpClient(smtpServer);
// 设置SMTP服务器的端口号和凭据
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(fromAddress, password);
// 发送邮件
smtpClient.Send(mailMessage);
}
}
```
请注意,发送邮件需要使用SMTP协议,因此需要设置SMTP服务器地址、端口号和发件人邮箱地址及其密码。在上述示例代码中,我们使用了`MailMessage`类来设置邮件的主题和正文,使用`SmtpClient`类来发送邮件。在实际使用中,您需要将示例代码中的发件人邮箱地址、密码、SMTP服务器地址、收件人邮箱地址、邮件主题和正文替换为您自己的信息。