moe
moe

Reputation: 5249

How to use HTML Format in sp_send_dbmail in asp.net

I am trying to send an email to some users but would like to use html format. I am loosing all the new lines and everything is showing as one line. Here is my current code:

   string body = "Hello " + fullName + Environment.NewLine + ",";
                body += "Your registration  has been approved. Here is your user name and password " + Environment.NewLine ;
                body += "User Name: " + usrname + Environment.NewLine;
                body += "Password: " + pass + Environment.NewLine;
                body += "Start Date: " + startDate + Environment.NewLine;
                body += "End Date: " + EndDate + Environment.NewLine;

                body += "Thanks";
                string toAddr = email.ToString();
                string mailMsg = body;

                string subject = "Registration Approved";
                string profile = "myProf";

                SqlConnection execMail = new SqlConnection("Data Source=XXXXXXXXX;Initial Catalog=msdb;Persist Security Info=True;User ID=xxxxxxxxxx;Password=xxxxxxxxxxx");
                execMail.Open();

                SqlCommand exec_cmd = new SqlCommand("sp_send_dbmail");
                exec_cmd.CommandType = CommandType.StoredProcedure;
                exec_cmd.Connection = execMail;

                exec_cmd.Parameters.AddWithValue("profile_name", profile);
                exec_cmd.Parameters.AddWithValue("recipients", toAddr);
                // exec_cmd.Parameters.AddWithValue("copy_recipients", ccAddr);
                // exec_cmd.Parameters.AddWithValue("blind_copy_recipients", bccAddr);
                exec_cmd.Parameters.AddWithValue("body", mailMsg);
                exec_cmd.Parameters.AddWithValue("subject", subject);

                exec_cmd.ExecuteNonQuery();

                exec_cmd.Dispose();
                execMail.Close();
                con.Close();
                con.Dispose();

Upvotes: 0

Views: 646

Answers (1)

Albarrant
Albarrant

Reputation: 26

You need to put html tags in your string body, example:

string body = "<h1>Hello" + fullName + Environment.NewLine + "</h1>";
                body += "<p>Your registration  has been approved. Here is your user name and password " + Environment.NewLine + "</p>";
                body += "<h3>User Name: " + usrname + Environment.NewLine+"</h3>";
                body += "<h3>Password: " + pass + Environment.NewLine+"</h3>";
                body += "<h3>Start Date: " + startDate + Environment.NewLine+"</h3>";
                body += "<h3>End Date: " + EndDate + Environment.NewLine+"</h3>";

                body += "<p>Thanks</p>";

then, in the parameters, you need to add:

exec_cmd.Parameters.AddWithValue("body_format", "HTML");

The default value is TEXT

Upvotes: 1

Related Questions