【发布时间】:2015-11-09 14:25:22
【问题描述】:
我有以下代码用于处理来自联系表单的电子邮件:
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Comment from SAM35 website";
myMessage.Body = mailbody;
myMessage.From = new MailAddress("xxxx@yyyy.com", "SAM35 Webamster");
myMessage.To.Add = new MailAddress("xxxx@zzzz.com");
这是从参考书中摘录的 - 我觉得这很合理。但是,在 Visual Studio Express 2015 中,对于 myMessage.To.Add 行,我收到警告消息
无法分配给“添加”,因为它是“方法”。
所以,在查看 Stack Overflow 是否有类似问题后,我尝试了
myMessage.To.Add ("xxxx@zzzz.com");
这消除了 VS 警告,但在运行时导致了未处理的异常。我会很感激这个问题的解决方法。
我将代码改为阅读
MailAddress ToAddress = new MailAddress("aaaaaa@bbbbb", "ccccccc");
myMessage.To.Add(ToAddress);
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
但还是有异常。
测试在 localhost 本地运行,使用嵌入了用户控件的 aspx 文件,在 VS 中按 Ctrl+F5,完成表单详细信息,然后点击发送按钮。当运行达到
时,会发生未处理的异常 MailMessage myMessage = new MailMessage();
以下是异常的详细信息:
System.FormatException 未被用户代码处理
HResult=-2146233033 消息=在 邮件标题:'@'。源 = 系统堆栈跟踪: 在 System.Net.Mail.MailAddressParser.ParseLocalPart(字符串数据,Int32& 索引,布尔值 expectAngleBracket,布尔值 期望多个地址) 在 System.Net.Mail.MailAddressParser.ParseAddress(字符串数据,布尔值 expectMultipleAddresses,Int32& 索引) 在 System.Net.Mail.MailAddressParser.ParseAddress(字符串数据) 在 System.Net.Mail.MailAddress..ctor(字符串地址,字符串 displayName,编码 displayNameEncoding) 在 System.Net.Mail.MailMessage..ctor() 在 c:\Websites\xxxxWebsite\Controls\ContactForm.ascx.cs:line 21 中的 Controls_ContactForm.btnSend_Click(Object sender, EventArgs e) 在 System.Web.UI.WebControls.Button.OnClick(EventArgs e) 在 System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串 eventArgument) 在 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串 事件参数) 在 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,字符串 eventArgument) 在 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) 在 System.Web.UI.Page.ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)
内部异常:
ContactForm.ascx.cs:line 21,导致异常,是这样一行:
MailMessage myMessage = new MailMessage();
我不明白为什么这会导致电子邮件标题中出现“@” - 再次建议将不胜感激。
如果有帮助,web.config 的 system.net 部分显示:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="yyyyy@gmail.com">
<network defaultCredentials="false" host="=smtp.gmail.com" port="587" userName="yyyy@gmail.com" password="qqqqqq"/>
</smtp>
</mailSettings>
</system.net>
【问题讨论】:
-
在您告诉我们未处理的异常是什么、发生的位置、提供相关代码等之前,我们无法为您提供帮助。
-
我有点怀疑这是直接从参考书上摘录的。
-
这本书是 Imar Spaanjaars 的“Beginning ASP.Net 3.5”。我承认我看错了剧本。这个项目不是我最好的时光。