C#如何将带有值的变量包含到要作为电子邮件发送的电子邮件正文中

时间:2013-12-10 10:25:24

标签: c# mysql email

我有一个'自动生成'随机数方法,该值存储在一个字符串中。我需要变量的值显示在mail.Body属性中。 这是我必须生成随机数的代码:

String id = " ";
Random rnd = new Random();

for(int a = 0; a <8; a++){
    id += rnd.Next(0,9);
}

这是我的邮件正文:

string Body = "Your New Value is " + id ;
mail.Body = Body;

但我收到的电子邮件只包含“您的新值为”Body,其中没有自动生成的值。

我该怎么做才能解决这个问题?谢谢!

3 个答案:

答案 0 :(得分:1)

试试这个C#-Code

Random rnd = new Random();
System.Text.StringBuilder result = new StringBuilder();

for (int a = 0; a < 8; a++)
{
    result.Append(rnd.Next(0,9)); 
}
mail.Body = string.Format("Your New Value is '{0}'", result.ToString());

由于行id += rnd.Next(0,9);,您的代码无效。您尝试将int连接到字符串。 它应该与此id += rnd.Next(0,9).ToString();一起使用 请不要使用'+'运算符或'+ ='运算符来连接字符串。请改用StringBuilder。

答案 1 :(得分:0)

尝试string.Format

string Body = string.Format("Your New Value is {0}", id);

另外,您确定id包含您的期望吗?

在号码生成器上调用.ToString()可能有所帮助:

String id = string.Empty;
Random rnd = new Random();

for(int a = 0; a <8; a++){
    id += rnd.Next(0,9).ToString(); {

此外,+ =每次都附加字符串......这就是你想要做的吗?

答案 2 :(得分:0)

public class GenerateRandomNum
{
    private static string id = "";

    public static string RandomNum()
    { 

   Random rnd = new Random();

   for(int a = 0; a <8; a++)
      {
      id +=(string)rnd.Next(0,9); 
      }
   }
}

class TestRandom
{
   public static void Main()
   {
       string Body = "Your New Value is " + GenerateRandomNum.RandomNum();
       mail.Body = Body;

   }
}

希望这会对你有所帮助