【问题标题】:trying to send email from database value尝试从数据库值发送电子邮件
【发布时间】:2014-02-24 20:24:25
【问题描述】:

我有一个方法将电子邮件地址作为字符串返回给发送电子邮件的代码块,但我收到错误消息:“指定的字符串不是电子邮件地址所需的格式。”

这是返回电子邮件地址的方法:

public static string getSignerByID(int signerID)
{
    using (dbPSREntities10 myEntities = new dbPSREntities10())
    {
        var thisId = myEntities.refAuthSigners.Where(x => x.refAuthSignerID == signerID).Select(x => x.NetworkEmail).ToList();

        var formattedValue = thisId.ToString();

        return formattedValue;

    }
}

这是发送电子邮件的代码:

//method to send approved email
    public static void sendApprovedEmail(string contactFirstName, string contactLastName, string contactEmail, int signer)
    {
        //Email one
        string fileName = HttpContext.Current.Server.MapPath("~/App_Data/ApprovedEmail.txt");
        string mailBody = File.ReadAllText(fileName);

        mailBody = mailBody.Replace("##ContactFirstName##", contactFirstName);
        mailBody = mailBody.Replace("##ContactLastName##", contactLastName);

        MailMessage myMessage = new MailMessage();
        myMessage.Subject = "PSR has been approved";
        myMessage.Body = mailBody;

        string signerEmailAddress = getSignerByID(signer);

        myMessage.From = new MailAddress("no-reply@test.com", "no-reply@test.com");
        myMessage.To.Add(new MailAddress(contactEmail));
        myMessage.To.Add(new MailAddress(signerEmailAddress));// this is the email address from the database that errors out.

        SmtpClient mySmtpClient = new SmtpClient();
        mySmtpClient.Send(myMessage);
    }

知道为什么变量“signerEmailAddress”不起作用吗?数据库中的值是 varchar(50) 并且绝对是有效的电子邮件地址。谢谢!

【问题讨论】:

  • getSignerById 返回的值不是有效的电子邮件地址。可能与使用List.ToString() 检索它的事实有关,这没有任何意义。学习调试和检查值。 codeproject.com/Articles/79508/…

标签: c# linq mailmessage


【解决方案1】:

thisId 将返回网络电子邮件列表

var thisId = myEntities.refAuthSigners
                       .Where(x => x.refAuthSignerID == signerID)
                       .Select(x => x.NetworkEmail)
                       .ToList();

调用ToString() 将返回列表的类型名称。比如:

"System.Collections.Generic.List`1[Namespace.NetworkEmail]"

这绝对不像电子邮件地址。可能您想使用FirstOrDefault() 而不是ToList()。这将返回您提供的 ID 的第一个签名者的网络地址。您应该检查返回值是否不为空,然后调用ToString()(如果您在网络电子邮件类型上覆盖了ToString())。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2015-02-14
    相关资源
    最近更新 更多