代码之家  ›  专栏  ›  技术社区  ›  JavierB

.NET。Mail未在office 365上发送任何经过两步验证的附加文件

  •  0
  • JavierB  · 技术社区  · 1 年前

    我使用这个发送电子邮件没有问题。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);
                    }
                }
            }
        }
    }````
    
    0 回复  |  直到 1 年前