Why is the variable empty when using MailMessage

60 views Asked by At

I have the following code:

try
{
    MailMessage mmSendEmail = new MailMessage();
    mmSendEmail.To.Add("[email protected]");
    mmSendEmail.From = new MailAddress("[email protected]");
    mmSendEmail.Subject = "Task#: " + s; //'s' is a query string from the URL of the page
    mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID='" + s +"' title='override'>task</a>";
    mmSendEmail.IsBodyHtml = true;

    SmtpClient scSend = new SmtpClient("mymailserverip");
    scSend.Send(mmSendEmail);
}

I receive the following email from the above code:

Subject: Task #: 0908090
Body: task ID: 0908090 <a href="http://mypage.com/page.aspx?ID=">task</a>

How come the ID is missing from the link but shows up in other place.

4

There are 4 answers

3
Thiago Avelino On BEST ANSWER

Try String Format for that:

String.Format("task ID: {0}.<br /><br /> <a href='http://mypage.com/page.aspx?ID={0}' title='override'>task</a>",s)
0
James Thorpe On

Note that your other attribute is missing too - you have a misplaced quote:

mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID='" + s +"' title='override'>task</a>";
                                                                                            ^

The highlighted quote should not be there, it should just be:

mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID=" + s +"' title='override'>task</a>";

A better solution would be to use String.Format as it cuts down on start/stop of the various quotes and makes issues like this easy to spot:

mmSendEmail.Body = String.Format("task ID: {0}.<br /><br /> <a href='http://mypage.com/page.aspx?ID={0}' title='override'>task</a>", s);
0
Sven Lauterbach On

I think the ' should be deleted:

mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID='" + s +"' title='override'>task</a>";

should be:

mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID=" + s +"' title='override'>task</a>";

otherwise the link is rendered like:

<a href='http://mypage.com/page.aspx?ID='s' title='override'>task</a>

... and this is not a valid href ;)

0
BvdVen On

I think the single quotes around the s in the querystring is ending your href. So replace it with:

mmSendEmail.Body = "task ID: " + s + ".<br /><br /> <a href='http://mypage.com/page.aspx?ID=" + s +"' title='override'>task</a>";