c# - 如何使用 Outlook 从 Visual Studio 发送电子邮件?
问题描述
我试图在我的 C# 应用程序中发送一封电子邮件。我添加了引用,我使用了语句,但似乎我没有添加所有内容。
这是代码:
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
namespace FileOrganizer
{
class Program
{
private void CreateMailItem()
{
//Outlook.MailItem mailItem = (Outlook.MailItem)
// this.Application.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "someone@example.com";
mailItem.Body = "This is the message.";
mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
}
}
}
解决方案
您可以使用以下代码发送电子邮件:
using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application app;
try
{
app = (Microsoft.Office.Interop.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
}
catch
{
app = new Microsoft.Office.Interop.Outlook.Application();
}
if (app == null)
{
return;
}
string stringHtmlBodyfromFile = File.ReadAllText(@"D:\test.html");
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as
Microsoft.Office.Interop.Outlook.MailItem;
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
mailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
mailItem.Subject = subject;
mailItem.To = “sendemail address”;
mailItem.Recipients.Add();
mailItem.HTMLBody = stringHtmlBodyfromFile;
mailItem.CC = “ccmailAddress”;
mailItem.Attachments.Add();
((Microsoft.Office.Interop.Outlook._MailItem)mailItem).Send();
}
}
}
推荐阅读
- wordpress - Worpress - 将任何页面设置为静态主页会导致包含多个超链接的内容
- html - 如何分段录制 UDP 流,FFmpeg
- c# - 如何在一行中调用实例方法之前将 Enum 转换为其基础类型?
- microsoft-graph-api - 访问 Sharepoint 资源失败并出现内部服务器错误 503
- php - 外键约束不兼容?
- corda - 使用 Gradle Test Runner 时如何控制日志级别
- winapi - MFC CFrameWndEx 大小控制以适应客户区覆盖工具栏和状态栏
- python - 为什么 seaborn.axes_style 在 Jupyter 上被重置?
- excel - 奇数/偶数行的交替公式
- python - 如何使用 Python 在 PowerBI 中制作可重现的数据样本?