我使用这个 .Net 程序发送电子邮件没有问题,但如果我附加文件,它永远不会到达。 在邮件服务器中显示邮件已正确到达,但不包含任何附件。 另一方面,如果使用相同的配置,我使用 PoweShell 发送一封带有附件的电子邮件,附件将毫无问题地到达。 谢谢
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
private string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
private string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private string tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
private string to = "[email protected]";
private string subject = "Test Email";
private string body = "This is a test email sent from C# Windows Forms using Microsoft Graph API";
private string token;
public Form1()
{
InitializeComponent();
}
private async void SendEmailButton_Click(object sender, EventArgs e)
{
try
{
token = await GetAccessToken();
var email = new
{
saveToSentItems = false,
message = new
{
subject = subject,
body = new
{
contentType = "Text",
content = body
},
toRecipients = new[]
{
new
{
emailAddress = new
{
address = to
}
}
}
},
attachments = new[]
{
new
{
odataType = "#microsoft.graph.fileAttachment",
name = "Hello.pdf",
contentBytes = Convert.ToBase64String(File.ReadAllBytes(@"c:\temp\Hello.pdf"))
}
}
};
var emailJson = Newtonsoft.Json.JsonConvert.SerializeObject(email);
await SendEmail(emailJson);
MessageBox.Show("Email sent successfully.");
}
catch (Exception ex)
{
MessageBox.Show("Error sending email: " + ex.Message);
}
}
private async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
var authority = $"https://login.microsoftonline.com/{tenantId}";
var tokenEndpoint = $"{authority}/oauth2/token";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("resource", "https://graph.microsoft.com")
});
var response = await client.PostAsync(tokenEndpoint, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
dynamic jsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent);
return jsonResponse.access_token;
}
else
{
throw new Exception("Failed to obtain access token.");
}
}
}
private async Task SendEmail(string emailJson)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var uri = "https://graph.microsoft.com/v1.0/users/[email protected]/sendMail";
var content = new StringContent(emailJson, Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync(uri, content);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Failed to send the email.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error sending email: " + ex.Message);
}
}
}
}
}````
您似乎正在使用 Microsoft Graph API 从 C# Windows 窗体应用程序发送电子邮件,并且您正在尝试将文件附加到电子邮件。
我已经尝试了我这边的代码,并且我能够发送邮件。
确保文件路径正确。在您的代码中,您将附加位于
@"c:\temp\Hello.pdf"
的文件。
确保该文件存在于该位置并且应用程序具有访问该文件的必要权限。
检查使用 Microsoft Graph API 发送带有附件的电子邮件所需的范围和权限。您可能需要更新应用程序注册以包含 Mail.Send
权限。
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private string clientId = "clientId";
private string clientSecret = "clientSecret";
private string tenantId = "tenantId";
private string to = "to mail";
private string from = "from mail";
private string token;
public Form1()
{
InitializeComponent();
}
private async void SendEmailButton_Click(object sender, EventArgs e)
{
try
{
// Step 1: Obtain Access Token
token = await GetAccessToken();
// Step 2: Prepare Email JSON Payload
var email = PrepareEmailJson();
// Step 3: Send Email
await SendEmail(email);
MessageBox.Show("Email sent successfully.");
}
catch (Exception ex)
{
MessageBox.Show("Error sending email: " + ex.Message);
}
}
private async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
var authority = $"https://login.microsoftonline.com/{tenantId}";
var tokenEndpoint = $"{authority}/oauth2/token";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("resource", "https://graph.microsoft.com")
});
var response = await client.PostAsync(tokenEndpoint, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
dynamic jsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent);
return jsonResponse.access_token;
}
else
{
throw new Exception("Failed to obtain access token.");
}
}
}
private string PrepareEmailJson()
{
// Step 2: Prepare Email JSON Payload
var email = new
{
saveToSentItems = false,
message = new
{
subject = subject,
body = new
{
contentType = "Text",
content = body
},
toRecipients = new[]
{
new
{
emailAddress = new
{
address = to
}
}
}
},
attachments = new[]
{
new
{
odataType = "#microsoft.graph.fileAttachment",
name = "YourFileName",
contentBytes = Convert.ToBase64String(File.ReadAllBytes(@"PathofYourFile")),
contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}
}
};
return Newtonsoft.Json.JsonConvert.SerializeObject(email);
}
private async Task SendEmail(string emailJson)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var uri = $"https://graph.microsoft.com/v1.0/users/{from}/sendMail";
var content = new StringContent(emailJson, Encoding.UTF8, "application/json");
try
{
// Step 3: Send Email
var response = await client.PostAsync(uri, content);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Failed to send the email.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error sending email: " + ex.Message);
}
}
}
}
}
结果