通过 SMTP 协议发送邮件,支持文本内容、附件,需配置邮箱 SMTP 服务器信息。
案例:邮件发送工具
using System.Net; using System.Net.Mail; public class EmailSender { // 发送邮件(支持附件) public static bool SendEmail(string smtpServer, int smtpPort, string username, string password, string toEmail, string subject, string body, string[] attachments = null) { try { // 创建邮件消息 MailMessage mail = new MailMessage(); mail.From = new MailAddress(username); // 发件人邮箱 mail.To.Add(toEmail); // 收件人邮箱 mail.Subject = subject; // 邮件主题 mail.Body = body; // 邮件内容 mail.IsBodyHtml = false; // 是否为HTML格式 // 添加附件 if (attachments != null && attachments.Length > 0) { foreach (string filePath in attachments) { if (File.Exists(filePath)) { mail.Attachments.Add(new Attachment(filePath)); } else { Console.WriteLine($"附件不存在:{filePath}"); } } } // 配置SMTP客户端 SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort); smtpClient.Credentials = new NetworkCredential(username, password); // 邮箱账号密码(或授权码) smtpClient.EnableSsl = true; // 启用SSL加密(多数SMTP服务器要求) smtpClient.Timeout = 5000; // 超时时间 // 发送邮件 smtpClient.Send(mail); Console.WriteLine("邮件发送成功!"); return true; } catch (Exception ex) { Console.WriteLine($"邮件发送失败:{ex.Message}"); return false; } } public static void Main(string[] args) { // 配置SMTP信息(以QQ邮箱为例) string smtpServer = "smtp.qq.com"; int smtpPort = 587; string username = "your-qq-email@qq.com"; // 你的QQ邮箱 string password = "your-authorization-code"; // QQ邮箱授权码(不是登录密码) string toEmail = "recipient@example.com"; // 收件人邮箱 string subject = "C# 邮件发送测试"; string body = "这是使用C# SMTP发送的测试邮件!"; string[] attachments = new string[] { @"C:\Temp\test.txt" }; // 附件路径(可选) // 发送邮件 SendEmail(smtpServer, smtpPort, username, password, toEmail, subject, body, attachments); } }
注意:
- QQ 邮箱需开启 SMTP 服务并获取授权码(设置→账户→开启 POP3/SMTP 服务);
- 其他邮箱(如 163、Gmail)需对应配置 SMTP 服务器和端口。