C# SmtpClient 发邮件

本文介绍了一个使用C#实现的异步邮件发送功能,通过定时任务定期发送邮件,并在本地记录详细的日志信息。示例代码展示了如何配置SMTP服务器,设置邮件内容,以及使用UTF8编码和异步发送方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net; 
using System.Threading;
using System.IO;
using System.Security.Cryptography;

namespace ConsoleApp348
{
    class Program
    {        
        static string logFullPath = Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
        static void Main(string[] args)
        {
            Timer emailTimer = new Timer(SendMailCallBack, null, 0, 1);
            Console.ReadLine();
        }
        
        private static void SendMailCallBack(object state)
        {
            string fromMail = "fromMail";
            string fromMailPwd = "fromMailPwd";
            string toMail = "toMail";
            MailExample(fromMail, fromMailPwd, toMail);
        }

        static void MailExample(string fromEmail, string fromEmailPwd, string toEmail)
        {            
            try
            {
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = "smtp.163.com";
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = new System.Net.NetworkCredential(fromEmail, fromEmailPwd);
                    using (MailMessage mail = new MailMessage())
                    {
                        mail.BodyEncoding = UTF8Encoding.UTF8;
                        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                        mail.From = new MailAddress(fromEmail);
                        mail.To.Add(new MailAddress(toEmail));
                        mail.Subject = $"This is the new test.Now is {DateTime.Now.ToString("mmssffff")}";
                        mail.Body = $"This is the mail body,And now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")}";
                        smtpClient.SendAsync(mail, $"Frommail:{fromEmail},ToMail:{toEmail},send email successfully!");
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;
                    }                        
                }                    
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                LogMessage(ex.StackTrace);
            }
        }

        private static void SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Console.WriteLine(e.UserState);
            LogMessage(e.UserState.ToString());
        }

        static void LogMessage(string msg)
        {            
            lock(logFullPath)
            {
                using (StreamWriter logWriterStream = new StreamWriter(logFullPath, true, UTF8Encoding.UTF8))
                {
                    logWriterStream.WriteLine($"Log message :{msg},now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
                }
            }           
        }
    }
}

 异步:public void SendAsync(MailMessage message, object userToken);

Sends the specified e-mail message to an SMTP server for delivery. This method  does not block the calling thread and allows the caller to pass an object to  the method that is invoked when the operation completes.

转载于:https://www.cnblogs.com/Fred1987/p/10903419.html

<think>好的,用户在使用C#SmtpClient发送邮件时遇到了Excel附件变成bin文件的问题。我需要仔细分析可能的原因,并提供正确的解决方案。 首先,用户提到的代码中引用了创建邮件和附件的部分,但示例中可能没有正确添加附件。根据引用内容,用户可能在邮件正文中插入了Excel数据转换的HTML,但没有正确附加Excel文件本身。附件处理不当可能导致文件类型被错误识别。 然后,我需要检查附件添加的方式是否正确。引用[4]提到使用Mailkit处理附件,但用户可能还在使用SmtpClient。正确的做法是使用Attachment类来添加附件,并设置ContentType为Excel的MIME类型,例如application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。如果未正确设置ContentType,邮件客户端可能无法识别文件类型,将其显示为bin文件。 另外,文件扩展名也很重要。添加附件时需要指定正确的文件名,确保包含.xlsx或.xls扩展名。如果附件名称不正确,接收方的邮件系统可能无法正确解析文件类型。 可能用户没有使用Attachment对象,而是错误地将文件内容插入到邮件正文中,导致附件丢失。需要确认代码中是否有使用mail.Attachments.Add来附加文件。 还需要检查发送邮件的代码是否符合标准,比如引用[2]中的示例使用了正确的发送流程。异常处理部分也需要确保不会影响附件的添加过程。 总结可能的原因:未正确添加附件对象、未设置正确的ContentType、文件名缺少扩展名。解决方案应包括使用Attachment类,设置正确的MIME类型和文件名,并确保代码正确添加附件到Attachments集合。</think>在使用C#的`SmtpClient`发送邮件时,Excel附件变为`.bin`文件的问题通常由**附件MIME类型未正确设置**或**文件扩展名缺失**导致。以下是分步解决方案: --- ### 步骤1:使用Attachment类添加附件 需通过`System.Net.Mail.Attachment`类显式指定附件类型: ```csharp // 创建Excel附件(注意指定ContentType) Attachment excelAttachment = new Attachment(excelFilePath); excelAttachment.ContentType = new ContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); mail.Attachments.Add(excelAttachment); ``` --- ### 步骤2:确保文件名包含扩展名 若通过流创建附件,需手动指定文件名: ```csharp // 通过文件流添加时明确指定名称和类型 FileStream fs = new FileStream(excelFilePath, FileMode.Open); Attachment streamAttachment = new Attachment(fs, "Report.xlsx", "application/vnd.ms-excel"); mail.Attachments.Add(streamAttachment); ``` --- ### 步骤3:完整邮件发送示例 ```csharp using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress("sender@example.com"); mail.To.Add("receiver@example.com"); mail.Subject = "带Excel附件的邮件"; mail.Body = "请查收附件"; // 添加Excel附件(自动识别MIME类型) Attachment attachment = new Attachment(@"D:\data\report.xlsx"); mail.Attachments.Add(attachment); using (SmtpClient smtp = new SmtpClient("smtp.example.com", 587)) { smtp.Credentials = new NetworkCredential("user", "password"); smtp.EnableSsl = true; smtp.Send(mail); } } ``` --- ### 关键原理 1. **MIME类型匹配**:Excel文件的正确MIME类型为: - `.xlsx`: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - `.xls`: `application/vnd.ms-excel`[^4] 2. **文件扩展名验证**:邮件客户端依赖文件名后缀识别文件类型,必须保证附件名称包含`.xlsx`或`.xls`[^5] ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值