【C#】“服务器响应为:mail from address must be same as authorization user”

本文详细介绍了如何使用C#发送带有附件的邮件,并解决了常见错误,包括如何开启POP3/SMTP和IMAP/SMTP服务,以及如何生成授权码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当用C#发送邮件的时候,出现以上的错误。

可能就是POP3/SMTP服务和IMAP/SMTP服务没有开启,那么开启这两个服务就可以使用第三方进行发邮件了。

如果还是无法,那么,就点击黄色框中的“生成授权码”。通过发送短信来生成授权码,把以前输入的邮箱登录密码改为生成的授权码就可以了。

开启步骤:登录网页版邮箱——》设置——》账户。然后就可以开启服务。

using System;
using System.Net.Mail;

namespace CS15_1
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化一个SmtpClient类
            SmtpClient myServer = new SmtpClient();
            myServer.Host = "smtp.qq.com";//在这里我使用的是qq邮箱,所以是smtp.qq.com,如果你使用的是126邮箱,那么就是smtp.126.com。

            MailMessage mailMessage = new MailMessage();//实例化一个发送邮件类
            mailMessage.From = new MailAddress("发件人邮箱");//发件人邮箱地址,方法重载不同,可以根据需求自行选择
            mailMessage.To.Add(new MailAddress("收件人邮箱"));//收件人邮箱地址
            mailMessage.Subject = "发送邮件测试";//邮件标题
            mailMessage.Body = "这是我给你发送的第一份邮件哦!";//邮件内容

           

            //发送一些文件到邮箱
            Attachment courseList = new Attachment(@"c:\myx.txt");
            mailMessage.Attachments.Add(courseList);
            courseList = new Attachment(@"c:\myp.jpg");
            mailMessage.Attachments.Add(courseList);

            myServer.EnableSsl = true;//使用安全加密连接
            myServer.UseDefaultCredentials = false;//不和请求一块发送
            myServer.Credentials = new System.Net.NetworkCredential("发件人邮箱", "密码或授权码");//验证发件人身份(发件人的邮箱,邮箱里的生成授权码);
            myServer.Send(mailMessage);//发送
            Console.Write("发送成功");
            Console.ReadKey();
        }
    }
}

 

只有web.config:内容如下哪里是提高画面质量的选项:<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- CAUTION! logging requires the ASP.NET IIS worker process to have write permission to the "log" folder. Among other options, you may grant the myrtille application pool ("IIS AppPool\MyrtilleAppPool") write permission to it (normally automatically set by the myrtille installer). --> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Log4net" /> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <section name="Myrtille.Web.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-1.5.1.25624" newVersion="1.5.2.14234" /> </dependentAssembly> </assemblyBinding> </runtime> <log4net> <root> <level value="DEBUG" /> <appender-ref ref="LogFileAppender" /> </root> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="log\Myrtille.Web.log" /> <param name="AppendToFile" value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> </log4net> <system.diagnostics> <trace autoflush="true" indentsize="4"> <listeners> <add name="Log4netTraceListener" type="Myrtille.Log.Log4netTraceListener, Myrtille.Common"> <!-- trace level (Information, Warning or Error). CAUTION! Information level will hinder performance --> <filter type="Myrtille.Log.Log4netTraceFilter, Myrtille.Common" initializeData="Error" /> </add> <!-- disable output window traces. CAUTION! enabling the default output window will hinder performance --> <remove name="Default" /> </listeners> </trace> <!-- enable the lines below for WCF tracing (caution as it will hinder performance). Use SvcTraceViewer.exe as viewer --> <!-- <sources> <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true"> <listeners> <add name="xml" /> </listeners> </source> <source name="System.ServiceModel.MessageLogging"> <listeners> <add name="xml" /> </listeners> </source> </sources> <sharedListeners> <add initializeData="log\Myrtille.Web.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="xml" /> </sharedListeners> --> </system.diagnostics> <system.web> <compilation defaultLanguage="C#" targetFramework="4.5" /> <!-- handle file upload/download up to 1GB. maxRequestLength is measured in kilobytes and executionTimeout in seconds --> <!-- handle querystrings up to 32KB (default 2KB). this can prove useful with large XHRs in HTML4 mode --> <httpRuntime requestValidationMode="4.5" targetFramework="4.5" maxRequestLength="1048576" maxQueryStringLength="32768" executionTimeout="360000" /> <pages enableViewState="false" validateRequest="false" enableEventValidation="false" clientIDMode="AutoID" /> <authorization> <allow users="*" /> </authorization> <authentication mode="None" /> <!-- CAUTION! cookieless="UseUri" allows multiple connections/tabs but, as the http session id is passed into the url, it also implies a risk of session spoofing to mitigate that risk, an authentication cookie is stored into the browser initiating the http session; any other client accessing the http session without it will be rejected please note that, even if the http session is cookieless, this mechanism requires cookies to be enabled client side the "cookieless=" attribute is really confusing because it's in fact the method used by the browser to send the http session id... and using a cookie is the standard way to do it if using myrtille within iframe(s) on a same page, cookieless="UseUri" must be used --> <sessionState mode="InProc" cookieless="UseUri" timeout="60" /> <!--<sessionState mode="InProc" cookieless="UseCookies" cookieName="AuthSecToken" timeout="60"/>--> <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="auto" uiCulture="auto" /> </system.web> <system.webServer> <defaultDocument> <files> <clear /> <add value="Default.aspx" /> </files> </defaultDocument> <urlCompression doDynamicCompression="false" /> <staticContent> <mimeMap fileExtension=".webp" mimeType="image/webp" /> </staticContent> <security> <requestFiltering> <!-- handle file upload/download up to 1GB. maxAllowedContentLength is measured in bytes --> <!-- handle querystrings up to 32KB (default 2KB). this can prove useful with large XHRs in HTML4 mode --> <requestLimits maxAllowedContentLength="1073741824" maxQueryString="32768" /> </requestFiltering> </security> <handlers> <add path="/handlers/SocketHandler.ashx" verb="*" name="SocketHandler" type="Myrtille.Web.SocketHandler" /> <add path="/handlers/AudioSocketHandler.ashx" verb="*" name="AudioSocketHandler" type="Myrtille.Web.AudioSocketHandler" /> <add path="/handlers/EventSourceHandler.ashx" verb="*" name="EventSourceHandler" type="Myrtille.Web.EventSourceHandler" /> <add path="/handlers/LongPollingHandler.ashx" verb="*" name="LongPollingHandler" type="Myrtille.Web.LongPollingHandler" /> </handlers> </system.webServer> <system.serviceModel> <client> <endpoint address="http://localhost:8080/Myrtille/RemoteSessionProcess" binding="wsDualHttpBinding" bindingConfiguration="wsDualHttpBindingCallback" contract="Myrtille.Services.Contracts.IRemoteSessionProcess" /> <endpoint address="http://localhost:8080/Myrtille/FileStorage" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingFileStream" contract="Myrtille.Services.Contracts.IFileStorage" /> <endpoint address="http://localhost:8080/Myrtille/PrinterService" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingFileStream" contract="Myrtille.Services.Contracts.IPrinterService" /> <endpoint address="http://localhost:8080/Myrtille/MFAAuthentication" binding="basicHttpBinding" contract="Myrtille.Services.Contracts.IMFAAuthentication" /> <endpoint address="http://localhost:8080/Myrtille/EnterpriseService" binding="basicHttpBinding" contract="Myrtille.Services.Contracts.IEnterpriseService" /> <endpoint address="http://localhost:8080/Myrtille/ApplicationPoolService" binding="basicHttpBinding" contract="Myrtille.Services.Contracts.IApplicationPoolService" /> </client> <bindings> <wsDualHttpBinding> <binding name="wsDualHttpBindingCallback" receiveTimeout="infinite" maxReceivedMessageSize="2147483647"> <security mode="None" /> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <reliableSession inactivityTimeout="infinite" /> </binding> </wsDualHttpBinding> <basicHttpBinding> <!-- buffer size: 64KB; max file size: 1GB --> <binding name="basicHttpBindingFileStream" transferMode="Streamed" messageEncoding="Mtom" maxBufferSize="65536" maxReceivedMessageSize="1073741824" closeTimeout="infinite" openTimeout="infinite" receiveTimeout="infinite" sendTimeout="infinite"> <security mode="None" /> </binding> </basicHttpBinding> </bindings> <!-- enable the lines below for WCF tracing (caution as it will hinder performance). Use SvcTraceViewer.exe as viewer --> <!-- <diagnostics> <messageLogging logEntireMessage="true" maxMessagesToLog="300" logMessagesAtServiceLevel="true" logMalformedMessages="true" logMessagesAtTransportLevel="true" /> </diagnostics> --> </system.serviceModel> <applicationSettings> <Myrtille.Web.Properties.Settings> <setting name="ConnectionServiceUrl" serializeAs="String"> <value>http://localhost:8008/MyrtilleAdmin/ConnectionService/</value> </setting> </Myrtille.Web.Properties.Settings> </applicationSettings> <appSettings> <!-- disable Visual Studio SignalR --> <add key="vs:EnableBrowserLink" value="false" /> <!-- disable Visual Studio Page Inspector --> <add key="PageInspector:ServerCodeMappingSupport" value="Disabled" /> <!-- providing access to the remote clipboard could be a security issue, it can be disabled below --> <add key="AllowRemoteClipboard" value="true" /> <!-- allow file transfer (requires a domain to be specified on connect) --> <add key="AllowFileTransfer" value="true" /> <!-- allow print download (through a pdf virtual printer). requires the "Myrtille PDF" printer to be installed --> <add key="AllowPrintDownload" value="true" /> <!-- allow remote session sharing (the session is broadcasted to all guests; read/write access is granted individually) --> <add key="AllowSessionSharing" value="true" /> <!-- allow audio plaback --> <add key="AllowAudioPlayback" value="true" /> <!-- share a session by url, with owner rights. set to false to disable and provide a session url spoofing protection. requires cookieless="UseUri" session state (system.web/sessionState section above) --> <!-- if a session is shared by url between different clients, each client is identified by a unique key instead of the http session id --> <add key="AllowShareSessionUrl" value="true" /> <!-- client ip protection --> <add key="ClientIPTracking" value="false" /> <!-- if the browser window/tab of the remote session owner is closed without disconnecting first, or if the connection is lost, delay (ms) before the remote session is disconnected by the gateway. value must be greater than "browserPulseInterval" defined into config.js (default 10 secs). 0 to disable --> <!-- this comes in addition but does not replace the session idle timeout, defined at the RDS level, which will disconnect the session after no user inputs are received for a given time, independently of Myrtille --> <add key="ClientIdleTimeout" value="0" /> <!-- audio buffer. improves the audio quality at the expense of a slight latency --> <add key="AudioBuffering" value="true" /> <!-- show or hide the toolbar (you can hide it if using your own UI) --> <add key="ToolbarEnabled" value="true" /> <!-- connect from a login page or url (you can disable it if using a connection API) --> <add key="LoginEnabled" value="true" /> <!-- if login is enabled, url of the login page (change it if using your own page or leave empty to use the default page) --> <add key="LoginUrl" value="" /> <!-- recycle the application pool when there is no active remote session; not applicable if using the enterprise mode --> <add key="IdleAppPoolRecycling" value="false" /> </appSettings> </configuration>
最新发布
07-20
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值