Что я пытаюсь сделать
Я хочу перетащить электронное письмо из Outlook PWA в приложение .NET 4.7.2 Winforms и занять электронное письмо в качестве. EML для дальнейшей обработки. Это работало в течение длительного времени. Но я бы предпочел не предоставлять моему приложению Winforms доступ к прочтению всего почтового ящика пользователя только тогда, когда мне нужен доступ к отдельным сообщениям, которые перетаскивает пользователь. /> Практически тот же вопрос, что и я, но не полезные ответы. < /p>
https://answers.microsoft.com/en-us/out ... df87222f6d> Ожидается
Мое приложение Winforms, чтобы захватить электронное письмо и иметь возможность сохранить файл .eml . Я знал, что это был бы другой метод, чем Outlook (Classic), но я подумал, что это будет возможно, потому что я могу без проблем перетащить электронное письмо из Outlook (New) на свой рабочий стол. Я не могу понять это.DragContext
DragImageBits
chromium/x-renderer-taint
FileDrop (0 bytes)
FileNameW (0 bytes)
FileName (0 bytes)
Chromium Web Custom MIME Data Format
Я могу собирать данные в формате данных Hromium Web MIME . Это содержит предмет электронной почты, идентификатор сообщения и некоторую другую информацию. Но не полные данные сообщений, которые можно преобразовать в .eml .
Но я не могу получить ссылки на файл .eml .
Наблюдения
Когда я перетаскиваю электронную почту (новый настольный). chrome_dragxxxxx_xxxxxxxxx . Эта папка содержит файл .eml . Я не думаю, что Windows вызывает API Graph и загружает сообщение. Похоже, что Outlook PWA загружает сообщение и передает его. /> Windows 11 < /li>
< /ul>
Что я делаю не так? Могу ли я просто не повторять, что перетаскивает электронное письмо с нового Outlook на мой рабочий стол Windows? < /P>
Это код для моего POC. Простое приложение Winforms, которое отображает диагностические данные.
my program.cs :
namespace EmailDragDropDemo
{
public class MainForm : Form
{
private Label dropLabel;
private TextBox formatsTextBox;
public MainForm()
{
this.Text = "Drag-and-Drop EML Demo";
this.Width = 400;
this.Height = 300;
dropLabel = new Label
{
Text = "Drag an email here",
AutoSize = false,
Dock = DockStyle.Top,
Height = 60,
TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
AllowDrop = true
};
formatsTextBox = new TextBox
{
Multiline = true,
ReadOnly = true,
Dock = DockStyle.Fill,
ScrollBars = ScrollBars.Vertical,
Font = new System.Drawing.Font("Consolas", 10),
WordWrap = false
};
dropLabel.DragEnter += DropLabel_DragEnter;
dropLabel.DragDrop += DropLabel_DragDrop;
this.Controls.Add(formatsTextBox);
this.Controls.Add(dropLabel);
}
private void DropLabel_DragEnter(object? sender, DragEventArgs e)
{
// Diagnostic: Show all available data formats
string[] formats = e.Data?.GetFormats() ?? new string[0];
string formatList = string.Join("\r\n", formats);
formatsTextBox.Text = formatList;
dropLabel.Text = "Available formats (see below):";
if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void DropLabel_DragDrop(object? sender, DragEventArgs e)
{
// Diagnostic: Show all available data formats and their contents
string[] formats = e.Data?.GetFormats() ?? new string[0];
string formatList = string.Join("\r\n", formats);
formatsTextBox.Text = formatList;
string details = "";
foreach (var format in formats)
{
try
{
var data = e.Data?.GetData(format);
if (data is string s)
{
details += $"Format: {format}\r\nContent (first 500 chars):\r\n{s.Substring(0, Math.Min(500, s.Length))}\r\n\r\n";
}
else if (data is string[] arr)
{
details += $"Format: {format}\r\nArray Content:\r\n{string.Join("\r\n", arr)}\r\n\r\n";
}
else if (data is System.IO.MemoryStream ms)
{
ms.Position = 0;
byte[] buffer = new byte[Math.Min(256, ms.Length)];
int read = ms.Read(buffer, 0, buffer.Length);
string hex = BitConverter.ToString(buffer, 0, read).Replace("-", " ");
details += $"Format: {format}\r\nMemoryStream (first {read} bytes as hex):\r\n{hex}\r\n";
// Try to decode as UTF-8 text if this is the Chromium Web Custom MIME Data Format
if (format.Contains("Chromium Web Custom MIME Data Format"))
{
ms.Position = 0;
using (var reader = new StreamReader(ms, System.Text.Encoding.Unicode, true, 1024, true)) // UTF-16LE
{
string text = reader.ReadToEnd();
details += $"Decoded as UTF-16LE text (all chars, including non-printable):\r\n";
foreach (char c in text)
{
if (char.IsControl(c) && c != '\r' && c != '\n')
details += $"[0x{((int)c):X2}]";
else
details += c;
}
details += "\r\n";
// Try to extract JSON from the decoded text
int jsonStart = text.IndexOf('{');
int jsonEnd = text.LastIndexOf('}');
if (jsonStart >= 0 && jsonEnd > jsonStart)
{
string json = text.Substring(jsonStart, jsonEnd - jsonStart + 1);
details += $"\r\nExtracted JSON:\r\n{json}\r\n";
// Optionally, try to pretty-print the JSON
try
{
var parsed = System.Text.Json.JsonDocument.Parse(json);
string pretty = System.Text.Json.JsonSerializer.Serialize(parsed, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
details += $"\r\nPretty-printed JSON:\r\n{pretty}\r\n";
}
catch (Exception ex)
{
details += $"\r\nJSON parse error: {ex.Message}\r\n";
}
}
else
{
details += "\r\nNo JSON object found in decoded text.\r\n";
}
}
}
details += "\r\n";
}
else if (data != null)
{
details += $"Format: {format}\r\nType: {data.GetType()}\r\n\r\n";
}
}
catch (Exception ex)
{
details += $"Format: {format}\r\nError: {ex.Message}\r\n\r\n";
}
}
// Show all details in a scrollable dialog
var diag = new Form { Text = "Drag Data Details", Width = 800, Height = 600 };
var tb = new TextBox { Multiline = true, ReadOnly = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, Text = details, Font = new System.Drawing.Font("Consolas", 10), WordWrap = false };
diag.Controls.Add(tb);
// Additional CF_HDROP/FileDrop diagnostics
if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
{
var fileDropData = e.Data.GetData(DataFormats.FileDrop);
string fileDropDetails = "==== CF_HDROP / FileDrop Diagnostics ====" + "\r\n";
if (fileDropData == null)
{
fileDropDetails += "FileDrop data is null.\r\n";
}
else if (fileDropData is string[] arr)
{
fileDropDetails += $"FileDrop data is string[] with {arr.Length} entries:\r\n";
foreach (var entry in arr)
{
fileDropDetails += $" {entry}\r\n";
}
}
else
{
fileDropDetails += $"FileDrop data type: {fileDropData.GetType()}\r\n";
try
{
fileDropDetails += fileDropData.ToString() + "\r\n";
}
catch { }
}
fileDropDetails += "==============================\r\n\r\n";
// Append to textbox
tb.AppendText("\r\n" + fileDropDetails);
}
diag.Show();
if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
{
var fileData = e.Data.GetData(DataFormats.FileDrop) as string[];
if (fileData != null)
{
foreach (var file in fileData)
{
string destPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Path.GetFileName(file));
File.Copy(file, destPath, true);
MessageBox.Show($"Saved: {destPath}\nExtension: {Path.GetExtension(file)}", "File Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
else
{
MessageBox.Show("No FileDrop data present. See available formats above.", "No FileDrop", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... pplication
Получите новую электронную почту Outlook как EML в приложении формы Windows ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Получите новую электронную почту Outlook как EML в приложении формы Windows
Anonymous » » в форуме C# - 0 Ответы
- 6 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Получите новую электронную почту Outlook как EML в приложении формы Windows
Anonymous » » в форуме C# - 0 Ответы
- 1 Просмотры
-
Последнее сообщение Anonymous
-