You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

发布应用时发送邮件触发System.FormatException异常求助

问题排查与解决

异常原因

这个System.FormatException是错误使用Console.WriteLine重载方法导致的:

  • 你调用了Console.WriteLine(string format, object arg0)重载,但第一个参数(格式字符串)里没有对应的占位符(比如{0}),.NET尝试格式化字符串时找不到匹配的参数索引,因此抛出该异常。
  • 代码里有两处问题:
    1. 邮件发送成功后的提示:Console.WriteLine("Your message has been successfully sent.", "Message");
    2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:43:16