C# 实现收发邮件
时间: 2023-07-12 11:18:33 浏览: 205
c# 实现发送邮件的功能
要在C#中实现收发邮件,可以使用.NET Framework提供的System.Net.Mail和System.Net.Pop3类库。以下是一些基本示例代码:
1. 发送邮件
```
using System.Net;
using System.Net.Mail;
public static void SendEmail(string to, string subject, string body)
{
MailMessage message = new MailMessage();
message.To.Add(to);
message.Subject = subject;
message.Body = body;
message.From = new MailAddress("your_email_address");
SmtpClient smtpClient = new SmtpClient("smtp_server_address");
smtpClient.Port = 587; //或者其他SMTP服务器端口号
smtpClient.Credentials = new NetworkCredential("your_email_address", "your_email_password");
smtpClient.EnableSsl = true; //启用SSL加密
smtpClient.Send(message);
}
```
2. 接收邮件
```
using System.Net;
using System.Net.Mail;
using System.Net.Pop3;
public static void ReceiveEmail()
{
Pop3Client pop3Client = new Pop3Client();
pop3Client.Connect("pop3_server_address", 995, true); //连接POP3服务器
pop3Client.Authenticate("your_email_address", "your_email_password"); //验证邮箱账号和密码
int count = pop3Client.GetMessageCount(); //获取邮件数量
for (int i = 1; i <= count; i++)
{
MailMessage message = pop3Client.GetMessage(i); //获取第i封邮件
//处理邮件内容
string from = message.From.ToString();
string subject = message.Subject;
string body = message.Body.ToString();
//标记为已读
pop3Client.DeleteMessage(i);
}
pop3Client.Disconnect(); //断开连接
}
```
注意:需要添加using System.Net和using System.Net.Mail引用,以便使用MailMessage、SmtpClient和Pop3Client等类。另外,POP3协议默认使用110端口,SSL加密协议默认使用995端口。
阅读全文