C# 邮件发送源码(支持附件)

C# 邮件发送源码(支持附件)

C#邮件发送,支持发送带附件的邮件

完整源码

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace EmailSenderApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("===== C# 邮件发送程序 =====");
            Console.WriteLine("支持文本/HTML内容和附件发送\n");

            try
            {
                // 1. 获取用户输入
                var emailConfig = GetEmailConfiguration();
                var recipients = GetRecipients();
                var subject = GetInput("邮件主题: ");
                var body = GetInput("邮件内容 (HTML格式请注明): ");
                bool isHtml = body.Contains("<html>") || body.Contains("<body>") || 
                             body.Contains("<div>") || body.ToLower().Contains("html");
                
                var attachments = GetAttachments();

                // 2. 发送邮件
                SendEmail(emailConfig, recipients, subject, body, isHtml, attachments);
                
                Console.WriteLine("\n邮件发送成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n错误: {ex.Message}");
                Console.WriteLine($"详细信息: {ex.InnerException?.Message}");
            }
            finally
            {
                Console.WriteLine("\n按任意键退出...");
                Console.ReadKey();
            }
        }

        /// <summary>
        /// 获取邮件配置信息
        /// </summary>
        static EmailConfig GetEmailConfiguration()
        {
            Console.WriteLine("===== 发件人配置 =====");
            return new EmailConfig
            {
                SenderEmail = GetInput("发件人邮箱: "),
                SenderName = GetInput("发件人名称: ", "发件人"),
                Password = GetPassword("发件人密码: "),
                SmtpServer = GetInput("SMTP服务器 (如: smtp.qq.com): "),
                Port = int.Parse(GetInput("SMTP端口 (如: 587): ", "587")),
                EnableSsl = bool.Parse(GetInput("启用SSL (true/false): ", "true"))
            };
        }

        /// <summary>
        /// 获取收件人列表
        /// </summary>
        static List<string> GetRecipients()
        {
            Console.WriteLine("\n===== 收件人配置 =====");
            var recipients = new List<string>();
            string input;
            do
            {
                input = GetInput("收件人邮箱 (输入空行结束): ");
                if (!string.IsNullOrWhiteSpace(input))
                {
                    try
                    {
                        var addr = new System.Net.Mail.MailAddress(input);
                        recipients.Add(addr.Address);
                    }
                    catch
                    {
                        Console.WriteLine("无效的邮箱格式,请重新输入");
                    }
                }
            } while (!string.IsNullOrWhiteSpace(input));

            if (recipients.Count == 0)
            {
                throw new ArgumentException("至少需要一个收件人");
            }

            return recipients;
        }

        /// <summary>
        /// 获取附件列表
        /// </summary>
        static List<string> GetAttachments()
        {
            Console.WriteLine("\n===== 附件配置 (可选) =====");
            var attachments = new List<string>();
            string input;
            do
            {
                input = GetInput("附件路径 (输入空行结束): ");
                if (!string.IsNullOrWhiteSpace(input))
                {
                    if (File.Exists(input))
                    {
                        attachments.Add(input);
                    }
                    else
                    {
                        Console.WriteLine("文件不存在,请重新输入");
                    }
                }
            } while (!string.IsNullOrWhiteSpace(input));

            return attachments;
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        static void SendEmail(EmailConfig config, List<string> recipients, 
                            string subject, string body, bool isHtml, 
                            List<string> attachments)
        {
            using (var message = new MailMessage())
            {
                // 设置发件人
                message.From = new MailAddress(config.SenderEmail, config.SenderName);
                
                // 添加收件人
                foreach (var recipient in recipients)
                {
                    message.To.Add(recipient);
                }
                
                // 设置邮件内容
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = isHtml;
                
                // 添加附件
                foreach (var file in attachments)
                {
                    var attachment = new Attachment(file);
                    message.Attachments.Add(attachment);
                }
                
                // 配置SMTP客户端
                using (var smtp = new SmtpClient(config.SmtpServer, config.Port))
                {
                    smtp.Credentials = new NetworkCredential(config.SenderEmail, config.Password);
                    smtp.EnableSsl = config.EnableSsl;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Timeout = 10000; // 10秒超时
                    
                    // 发送邮件
                    Console.WriteLine("\n正在发送邮件...");
                    smtp.Send(message);
                }
            }
        }

        // 辅助方法:获取用户输入
        static string GetInput(string prompt, string defaultValue = "")
        {
            Console.Write(prompt);
            if (!string.IsNullOrEmpty(defaultValue))
            {
                Console.Write($" (默认: {defaultValue}): ");
            }
            else
            {
                Console.Write(": ");
            }
            
            var input = Console.ReadLine();
            return string.IsNullOrWhiteSpace(input) ? defaultValue : input;
        }

        // 辅助方法:安全获取密码
        static string GetPassword(string prompt)
        {
            Console.Write(prompt);
            var password = new StringBuilder();
            ConsoleKeyInfo key;
            
            do
            {
                key = Console.ReadKey(true);
                
                // 退格键处理
                if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                {
                    password.Remove(password.Length - 1, 1);
                    Console.Write("\b \b");
                }
                // 回车键结束输入
                else if (key.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                // 只接受可打印字符
                else if (key.KeyChar >= 32 && key.KeyChar <= 126)
                {
                    password.Append(key.KeyChar);
                    Console.Write("*");
                }
            } while (true);
            
            return password.ToString();
        }
    }

    /// <summary>
    /// 邮件配置类
    /// </summary>
    class EmailConfig
    {
        public string SenderEmail { get; set; }
        public string SenderName { get; set; }
        public string Password { get; set; }
        public string SmtpServer { get; set; }
        public int Port { get; set; }
        public bool EnableSsl { get; set; }
    }
}

使用说明

1. 基本功能

2. 使用步骤

  1. 运行程序
  2. 输入发件人邮箱、名称、密码
  3. 输入SMTP服务器地址和端口
  4. 选择是否启用SSL
  5. 输入收件人邮箱(多个收件人分行输入)
  6. 输入邮件主题和内容
  7. 添加附件(可选)
  8. 程序自动发送邮件

3. 常见邮箱配置

邮箱服务 SMTP服务器 端口 SSL
QQ邮箱 smtp.qq.com 587
163邮箱 smtp.163.com 25
Gmail smtp.gmail.com 587
Outlook smtp-mail.outlook.com 587
企业邮箱 咨询管理员 25/587 是/否

4. 常见问题解决

问题1:认证失败

问题2:连接超时

问题3:附件过大

高级功能扩展

1. 添加密送(Bcc)功能

// 在SendEmail方法中添加
foreach (var bcc in bccList)
{
    message.Bcc.Add(bcc);
}

2. 添加邮件模板

// 使用HTML模板
string template = File.ReadAllText("template.html");
string body = template.Replace("{content}", userContent);

3. 异步发送

// 使用async/await
public async Task SendEmailAsync(...)
{
    await smtp.SendMailAsync(message);
}

4. 添加邮件日志

// 记录发送日志
File.AppendAllText("email_log.txt", 
    $"{DateTime.Now}: 发送邮件至 {string.Join(",", recipients)}\n");

参考代码 C# 邮件发送 源码下载(可带附件) www.youwenfan.com/contentcns/116200.html

安全注意事项

  1. 不要硬编码密码:实际应用中应从安全存储获取
  2. 使用加密连接:始终启用SSL/TLS
  3. 限制发送频率:避免被识别为垃圾邮件
  4. 验证收件人:防止邮件注入攻击
  5. 处理敏感数据:邮件内容加密

项目结构

EmailSender/
├── Program.cs         # 主程序
├── EmailConfig.cs     # 配置类
├── App.config         # 配置文件(可选)
└── attachments/       # 附件目录(可选)

此代码可直接复制到Visual Studio中使用,需要添加System.Net.Mail引用(在.NET Framework中默认包含,.NET Core需安装NuGet包System.Net.Mail)。

专注于matlab/simulink,电子电路,编程