发布应用时发送邮件触发System.FormatException异常求助
问题排查与解决
异常原因
这个System.FormatException是错误使用Console.WriteLine重载方法导致的:
- 你调用了
Console.WriteLine(string format, object arg0)重载,但第一个参数(格式字符串)里没有对应的占位符(比如{0}),.NET尝试格式化字符串时找不到匹配的参数索引,因此抛出该异常。 - 代码里有两处问题:
- 邮件发送成功后的提示:
Console.WriteLine("Your message has been successfully sent.", "Message"); - catch块中的异常输出:
Console.WriteLine(ex.Message, "Message");
- 邮件发送成功后的提示:
- 仅发布时触发的原因是调试环境的异常捕获策略或运行时行为差异掩盖了问题,发布模式下代码优化会让错误直接暴露。
解决办法
修改两处Console.WriteLine的调用逻辑,匹配正确的方法重载:
1. 成功提示的修正
去掉多余的第二个参数,使用单参数重载:
Console.WriteLine("Your message has been successfully sent.");
2. 异常输出的修正
如果需要保留"Message"前缀,给格式字符串添加占位符;不需要的话直接输出异常信息:
// 带前缀的写法 Console.WriteLine("Message: {0}", ex.Message); // 直接输出异常信息 Console.WriteLine(ex.Message);
修正后的完整代码片段
using (StreamReader reader = new StreamReader(FilePath)) { string MailText = reader.ReadToEnd(); reader.Close(); try { //Using COM to send email Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); //替换文本内容 MailText = MailText.Replace("[Fecha]", Convert.ToString(dateTime)); MailText = MailText.Replace("[Cantidad]", Convert.ToString(VariablesGlobals.OpMgr)+" de "+Convert.ToString(VariablesGlobals.Dir)); //待补充收件人及抄送人 mail.To = "correo.prueba@outlook.com"; mail.Subject = "Actualización Programa [DataInformer] " + mes + ", " + Convert.ToString(dia); mail.HTMLBody = MailText; mail.Importance = Outlook.OlImportance.olImportanceHigh;//设置邮件高优先级 ((Outlook._MailItem)mail).Send(); Console.WriteLine("Your message has been successfully sent."); } catch (Exception ex) { Console.WriteLine("Message: {0}", ex.Message); } }
内容的提问来源于stack exchange,提问作者Ricardo PP
相关产品推荐
相关产品推荐

