您可以使用以下代码片段来使用ASP.NET C#向Outlook发送电子邮件:
using Microsoft.Office.Interop.Outlook;// 创建Outlook应用程序对象Application outlookApp = new Application();// 创建邮件项MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);// 设置邮件项的属性mailItem.Subject = "测试邮件";mailItem.Body = "这是一封测试邮件";// 添加收件人Recipient recipient = mailItem.Recipients.Add("recipient@example.com");recipient.Type = (int)OlMailRecipientType.olTo;// 添加附件string attachmentPath = @"C:\path\to\attachment.txt";mailItem.Attachments.Add(attachmentPath, Type.Missing, Type.Missing, Type.Missing);// 发送邮件mailItem.Send();// 释放资源System.Runtime.InteropServices.Marshal.ReleaseComObject(mailItem);System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookApp);mailItem = null;outlookApp = null;但是请注意,这种方法将依赖于安装了Microsoft Outlook的机器,并且Outlook应用程序对象将在您的代码中创建一个新的Outlook实例。因此,这种方法仅适用于运行代码的计算机上已经安装了Outlook的情况。
另外,您还需要在项目中引用Microsoft.Office.Interop.Outlook程序集,可以通过Visual Studio的NuGet包管理器来安装它。
如果您想要发送邮件而无需依赖于Outlook应用程序,您可以使用SMTP服务器来发送电子邮件。以下是一个使用SMTP发送电子邮件的示例代码:
using System.Net;using System.Net.Mail;// 创建SMTP客户端SmtpClient smtpClient = new SmtpClient("smtp.example.com", 587);smtpClient.EnableSsl = true;smtpClient.UseDefaultCredentials = false;smtpClient.Credentials = new NetworkCredential("username", "password");// 创建邮件对象MailMessage mailMessage = new MailMessage();mailMessage.From = new MailAddress("sender@example.com");mailMessage.To.Add("recipient@example.com");mailMessage.Subject = "测试邮件";mailMessage.Body = "这是一封测试邮件";// 添加附件string attachmentPath = @"C:\path\to\attachment.txt";mailMessage.Attachments.Add(new Attachment(attachmentPath));// 发送邮件smtpClient.Send(mailMessage);在这种情况下,您将使用SMTP客户端(例如Gmail或Outlook.com)的服务器和凭据来发送电子邮件。这种方法不依赖于安装了Outlook的计算机,并且更适用于Web应用程序等无法访问本地Outlook应用程序的场景。