尝试从数据库值发送电子邮件

时间:2014-01-31 23:28:53

标签: c# linq mailmessage

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

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

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),绝对是有效的电子邮件地址。谢谢!

1 个答案:

答案 0 :(得分:3)

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())。