温馨提示×

如何使用asp.net c#向outlook发送电子邮件

小云
136
2023-09-27 09:46:53
栏目: 编程语言

您可以使用以下代码片段来使用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应用程序的场景。

0