简体   繁体   English

Blazor Wasm 发送邮件抛出异常 System.PlatformNotSupportedException: System.Net.Dns:GetHostByName 在此平台上不受支持

[英]Blazor Wasm sending mail throw exception System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform

I'm trying to send an email from a Blazor WASM app but I'm getting this exception我正在尝试从 Blazor WASM 应用程序发送电子邮件,但出现此异常

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Message could not be sent. Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:无法发送消息。 System.Net.Mail.SmtpException: Message could not be sent. System.Net.Mail.SmtpException:无法发送消息。 ---> System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform. ---> System.PlatformNotSupportedException: System.Net.Dns:GetHostByName 在此平台上不受支持。 at System.Net.Sockets.TcpClient..ctor (System.String hostname, System.Int32 port) <0x44e7108 + 0x000aa> in :0 at System.Net.Mail.SmtpClient.SendInternal (System.Net.Mail.MailMessage message) <0x44e6a78 + 0x00016> in :0 at System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) <0x44e19c0 + 0x000c4> in :0 --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) <0x44e19c0 + 0x000ee> in :0 at MusicSellingApp.Client.Pages.ArtistProfile.SendMail () [0x000a3] in C:\\Users\\ismailghedamsi\\Source\\Repos\\MusicSellingPlatformVeille\\MusicSellingApp\\Client\\Pages\\ArtistProfile.razor:33 at MusicSellingApp.Client.Pages.ArtistProfile.OnInitializedAsync () [0x0000f] in C:\\Users\\ismailghedamsi\\Source\\Repos\\MusicSellingPlatformVeille\\MusicSellingApp\\Client\\Pages\\ArtistProfile.razor:38 at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x3f6d608 + 0x0013a> in :0在 System.Net.Sockets.TcpClient..ctor(System.String 主机名,System.Int32 端口)<0x44e7108 + 0x000aa> 中:0 在 System.Net.Mail.SmtpClient.SendInternal(System.Net.Mail.MailMessage 消息) <0x44e6a78 + 0x00016> in :0 at System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) <0x44e19c0 + 0x000c4> in :0 ---内部异常堆栈跟踪结束---在系统.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message) <0x44e19c0 + 0x000ee> in :0 at MusicSellingApp.Client.Pages.ArtistProfile.SendMail () [0x000a3] in C:\\Users\\ismailghedamsi\\Source \\Repos\\MusicSellingPlatformVeille\\MusicSellingApp\\Client\\Pages\\ArtistProfile.razor: 33 at MusicSellingApp.Client.Pages.ArtistProfile.OnInitializedAsync () [0x0000f] 在 C:\\Users\\ismailghedamsi\\Source\\Repos\\MusicSellingSellingPlatform\\MusicSellingApp.Client.Pages.ArtistProfile.OnInitializedAsync \\ArtistProfile.razor:38 在 Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x3f6d608 + 0x0013a> 中:0

This is my razor file这是我的剃须刀文件

@page "/artistProfile"
@inject ILocalStorageService storageService
@using System.Net.Mail
<h2>@(artist == null)</h2>
<UserInfoComponent User="@artist" />

@code{
    Artist artist;

    public void SendMail()
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress("mymail@gmail.com");
                mail.To.Add("mymail@gmail.com");
                mail.Subject = "Sending mail";
                mail.Body = "<h2>this is a mail body</h2>";
                mail.IsBodyHtml = true;
                using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                {
                    smtp.Credentials = new System.Net.NetworkCredential("mymail@gmail.com", "mypassword");
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
    protected override async Task OnInitializedAsync()
    {
        SendMail();
        artist = await storageService.GetItemAsync<Artist>("loggedUser");
    }

}

The same c# code is working on a console app相同的 c# 代码正在控制台应用程序上运行

Even though Blazor (wasm) can run C# code direct on the browser, it's limited by the browser capabilities, send an e-mail is not something the browser can do.尽管 Blazor (wasm) 可以直接在浏览器上运行 C# 代码,但它受到浏览器功能的限制,发送电子邮件不是浏览器可以做的。 In this cases generally what happens is that a PlatformNotSupportedException is throw or you'll get a warning on visual studio CA1416: Validate platform compatibility .在这种情况下,通常会发生PlatformNotSupportedException抛出,否则您将在 Visual Studio CA1416上收到警告:验证平台兼容性 The alternative in this case would be call a server API that sends the e-mail.在这种情况下,另一种方法是调用发送电子邮件的服务器 API。

@Guilherme's answer is mostly correct in that Blazor (WASM) cannot use classes like SmtpClient, which are not supported on the browser platform. @Guilherme 的回答大部分是正确的,因为 Blazor (WASM) 不能使用浏览器平台不支持的类,如 SmtpClient。 However, that is not the entire story.然而,这并不是故事的全部。 There is a workaround that can be used for very basic email needs that leverages the old-school technique of using "mailto:" anchor links combined with injecting the IJSRuntime.有一种解决方法可用于非常基本的电子邮件需求,它利用了使用“mailto:”锚链接结合注入 IJSRuntime 的老派技术。

Let me provide some sample code in case it helps the next developer that comes across this post.让我提供一些示例代码,以防它对遇到这篇文章的下一个开发人员有所帮助。 Just keep in mind this technique uses the querystring and the MAILTO function has a limit of around 2000 characters .请记住,此技术使用查询字符串,而 MAILTO 函数的限制约为 2000 个字符 Exceeding this limit may prevent the message from being opened in the user's default mail app.超过此限制可能会阻止在用户的默认邮件应用程序中打开邮件。

From a button click or other trigger, invoke a function in your view model (or c# code):通过单击按钮或其他触发器,在您的视图模型(或 C# 代码)中调用一个函数:

protected void SendLocalEmail(string toEmailAddress, string subject, string body)
{
    JsRuntime.InvokeAsync<object>("blazorExtensions.SendLocalEmail",
      new object[] { toEmailAddress, subject, body });
}

Then, in your wwwroot folder, you should have a corresponding .js file (ie GlobalFunctions.js) that contains the corresponding JavaScript SendLocalEmail() function such as:然后,在您的 wwwroot 文件夹中,您应该有一个相应的 .js 文件(即 GlobalFunctions.js),其中包含相应的 JavaScript SendLocalEmail() 函数,例如:

window.blazorExtensions = {
  SendLocalEmail: function (mailto, subject, body) {
    var link = document.createElement('a');
    var uri = "mailto:" + mailto + "?";
    if (!isEmpty(subject)) {
        uri = uri + "subject=" + subject;
    }

    if (!isEmpty(body)) {
        if (!isEmpty(subject)) { // We already appended one querystring parameter, add the '&' separator
            uri = uri + "&"
        }

        uri = uri + "body=" + body;
    }

    uri = encodeURI(uri);
    uri = uri.substring(0, 2000); // Avoid exceeding querystring limits.
    console.log('Clicking SendLocalEmail link:', uri);

    link.href = uri;
    document.body.appendChild(link); // Needed for Firefox
    link.click();
    document.body.removeChild(link);
  }
};

function isEmpty(str) {
  return (!str || str.length === 0);
}

Finally, be sure you include a reference to your .js file in the index.html file (also in the wwwroot folder):最后,确保在 index.html 文件(也在 wwwroot 文件夹中)中包含对 .js 文件的引用:

<script src="GlobalFunctions.js"></script>

I place the above script reference below this line:我将上面的脚本引用放在这一行下面:

<script>navigator.serviceWorker.register('service-worker.js');</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 多线程,ApartmentState.MTA 点异常:System.PlatformNotSupportedException:COM 此平台不支持互操作 - MultiThread, ApartmentState.MTA point Exception : System.PlatformNotSupportedException: COM Interop is not supported on this platform System.PlatformNotSupportedException AesCryptoServiceProvider - System.PlatformNotSupportedException AesCryptoServiceProvider 将TransactionScope与抛出OracleManagedDataAccess的System.PlatformNotSupportedException一起使用:“此平台不支持该操作。” - Use TransactionScope with OracleManagedDataAccess throwing System.PlatformNotSupportedException: 'Operation is not supported on this platform.' Windows Mobile 6 System.PlatformNotSupportedException - Windows Mobile 6 System.PlatformNotSupportedException System.PlatformNotSupportedException 来自 CompileAssemblyFromSource - System.PlatformNotSupportedException from CompileAssemblyFromSource 调用Assembly.ReflectionOnlyLoadFrom时发生System.PlatformNotSupportedException异常 - System.PlatformNotSupportedException exception when calling Assembly.ReflectionOnlyLoadFrom System.PlatformNotSupportedException 在运行时编译 C# 代码 .NET Core - System.PlatformNotSupportedException Compiling C# code at runtime .NET Core PlatformNotSupportedException:此平台不支持 System.Data.OleDb - PlatformNotSupportedException: System.Data.OleDb is not supported on this platform 抛出异常:“System.PlatformNotSupportedException”。 如何在 dotnet core 3.1 中加密和解密安全字符串? - Exception thrown: 'System.PlatformNotSupportedException' . How to encrypt and decrypt securestring in dotnet core 3.1? 领域Xamarin.Android单元测试System.PlatformNotSupportedException - Realm Xamarin.Android Unit Test System.PlatformNotSupportedException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM