新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

怎样使用asp.net c#向outlook发送电子邮件,怎样使用灭火器

发布时间:2023-09-27 09:46:53

怎样使用asp.net c#向outlook发送电子邮件

您可使用以下代码片断来使用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	ottachment.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	ottachment.txt";
mailMessage.Attachments.Add(new Attachment(attachmentPath));
// 发送邮件
smtpClient.Send(mailMessage);

在这类情况下,您将使用SMTP客户端(例如Gmail或Outlook.com)的服务器和凭据来发送电子邮件。这类方法不依赖于安装了Outlook的计算机,并且更适用于Web利用程序等没法访问本地Outlook利用程序的场景。