1

I am a new ASP.NET developer and I am developing a traning management system that will send a weekly email notifications to the employees in my department to participate in a weekly short training quiz. Everything works fine. And for sending the email notifications, of course I am using the C# Mail function. The email is a text-based email, and it will be included the link to the new quiz on a weekly basis.

Now, I want to make this text-based email as a an image-based email. There is a speicific part in that image will be as a link to the new quiz. So every week there will be a new link under that part of the image. I am struggling with this part and I don't know how to modify my C# Mail function to deal with it. This is my first time to send an image using C# Mail function. I searched a lot on Google and I got confused. FYI, I designed my Mail function to deal with sending the same email to more than 200 users by spliting them into lists of 10 users as shown below.

Could you please help me in modifying the code shown below to deal with sending that image? Let us assume that we have any image.

C# Code:

protected void Page_Load(object sender, EventArgs e)
    {
        Send();
    }


    protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
    {
        SmtpClient sc = new SmtpClient("Mail Server");
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("Test@MailServer.com", "TestSystem");


            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = MessageBody;
            msg.IsBodyHtml = isBodyHtml;
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    protected void SendEmailTOAllUser()
    {
        string connString = "Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            var sbEmailAddresses = new System.Text.StringBuilder(2000);
            string quizid = "";

            // Open DB connection.
            conn.Open();

            string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        // There is only 1 column, so just retrieve it using the ordinal position
                        quizid = reader["mQuizID"].ToString();

                    }
                }
                reader.Close();
            }

            string cmdText2 = "SELECT Username FROM dbo.employee";
            using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        var sName = reader.GetString(0);
                        if (!string.IsNullOrEmpty(sName))
                        {
                            if (sbEmailAddresses.Length != 0)
                            {
                                sbEmailAddresses.Append(",");
                            }
                            // Just use the ordinal position for the user name since there is only 1 column
                            sbEmailAddresses.Append(sName).Append("@MailServer.com");
                        }
                    }
                }
                reader.Close();
            }

            string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
            using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
            {
                // Add the parameter to the command
                var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);

                var sEMailAddresses = sbEmailAddresses.ToString();
                string link = "<a href='http://localhost/test.aspx?testid=" + quizid + "'> Click here to participate </a>";
                string body = @".................................. ";

                int sendCount = 0;
                List<string> addressList = new List<string>(sEMailAddresses.Split(','));
                StringBuilder addressesToSend = new StringBuilder();

                if (!string.IsNullOrEmpty(quizid))
                {
                    for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
                    {
                        sendCount++;
                        if (addressesToSend.Length > 0)
                            addressesToSend.Append(",");

                        addressesToSend.Append(addressList[userIndex]);
                        if (sendCount == 10 || userIndex == addressList.Count - 1)
                        {
                            SendEmail(addressesToSend.ToString(), "", "Notification", body, true);
                            addressesToSend.Clear();
                            sendCount = 0;
                        }
                    }

                    // Update the parameter for the current quiz
                    oParameter.Value = quizid;
                    // And execute the command
                    cmd.ExecuteNonQuery();
                }
            }
            conn.Close();
        }
    }

UPDATE:

Guys, you did not get what I mean. The whole email will be an image, and small part like small circle of that image will be as a hyperlink not the whole image. And that link we will be changed every week such as default.aspx/testid=12 and so on. So how to do that?

UPDATE #2: I updated the following part of my code to include image but I am facing a problem with adding the AlternateViews.ADD(av). How to fix this?

string body = @"........................";
                            ";
                AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource("~/EmailNotification.jpg");
                lr.ContentId="image1";
                av.LinkedResources.Add(lr);
                //msg.AlternateViews.Add(av);

UPDATE #3:

protected void Page_Load(object sender, EventArgs e)
    {
        Send();
    }


    protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml, AlternateView av)
    {
        SmtpClient sc = new SmtpClient("Mail Adderess");
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("test@MailServer.com", "TestSystem");


            //QuizLink is appSetting inside your web config
            string newLink = System.Configuration.ConfigurationManager.AppSettings["QuizLink"].ToString();

            string html = "<h1>Quiz!</h1><img src=/fulladdress/someimage.png usemap ='#clickMap'>";
                   html += "<map id =\"clickMap\" name=\"clickMap\">" +
                            "<area shape =\"rect\" coords =\"0,0,82,126\" href ="+ newLink +" alt=\"Quiz\" /></map>";


            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = MessageBody;
            msg.IsBodyHtml = isBodyHtml;
            msg.AlternateViews.Add(av);
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    protected void Send()
    {
        string connString = "Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            var sbEmailAddresses = new System.Text.StringBuilder(2000);
            string quizid = "";

            // Open DB connection.
            conn.Open();

            string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        // There is only 1 column, so just retrieve it using the ordinal position
                        quizid = reader["mQuizID"].ToString();

                    }
                }
                reader.Close();
            }

            string cmdText2 = "SELECT Username FROM dbo.employee";
            using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        var sName = reader.GetString(0);
                        if (!string.IsNullOrEmpty(sName))
                        {
                            if (sbEmailAddresses.Length != 0)
                            {
                                sbEmailAddresses.Append(",");
                            }

                            sbEmailAddresses.Append(sName).Append("@MailServer");
                        }
                    }
                }
                reader.Close();
            }

            string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
            using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
            {
                // Add the parameter to the command
                var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);

                var sEMailAddresses = sbEmailAddresses.ToString();
                string link = "<a href='http://localhost/Test.aspx?testid=" + quizid + "'> Click here to participate </a>";
                string body = @".............................";
                AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource("~/EmailNotification.jpg", MediaTypeNames.Image.Jpeg);
                lr.ContentId="image1";
                av.LinkedResources.Add(lr);
                //msg.AlternateViews.Add(av);


                int sendCount = 0;
                List<string> addressList = new List<string>(sEMailAddresses.Split(','));
                StringBuilder addressesToSend = new StringBuilder();

                if (!string.IsNullOrEmpty(quizid))
                {
                    for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
                    {
                        sendCount++;
                        if (addressesToSend.Length > 0)
                            addressesToSend.Append(",");

                        addressesToSend.Append(addressList[userIndex]);
                        if (sendCount == 10 || userIndex == addressList.Count - 1)
                        {
                            SendEmail(addressesToSend.ToString(), "", "Notification", body, true, av);
                            addressesToSend.Clear();
                            sendCount = 0;
                        }
                    }

                    // Update the parameter for the current quiz
                    oParameter.Value = quizid;
                    // And execute the command
                    cmd.ExecuteNonQuery();
                }
;
                }


            }
            conn.Close();
        }
    }
Technology Lover
  • 143
  • 1
  • 5
  • 22

3 Answers3

2

You have to send Image as part HTML. Use following code

myemail.Body = "<h1>Quiz!</h1><img src=/fulladdress/someimage.png onclick="location.href='myPage.html'">";

myemail.IsBodyHtml = true; //Send this as plain-text

I have taken help from these links. Hope it would be also Helpfull to you

  1. http://www.intstrings.com/ramivemula/c/how-to-send-an-email-using-c-net-with-complete-features/

  2. Send a email with a HTML file as body (C#)

UPDATE

Store your Quiz URL in Database, so that it could be changed every week Use image map to create a part of image clickable. Build the html as below.

//in this case your newLink would be default.aspx/testid=12
string newLink = GetNewLinkFromDB();


string html = "<h1>Quiz!</h1><img src=/fulladdress/someimage.png usemap ="#clickMap">";
html += "<map id =\"clickMap\" name=\"clickMap\">
<area shape =\"rect\" coords =\"0,0,82,126\" href ="+ newLink +" alt=\"Quiz\" />
</map>"

Update 2

protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
    {
        SmtpClient sc = new SmtpClient("MailServer");
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("test@mailServer.com", "TestSystem");


            //QuizLink is appSetting inside your web config
            string newLink = System.Configuration.ConfigurationManager.AppSettings["QuizLink"].ToString();


    string html = "<h1>Quiz!</h1><img src=/fulladdress/someimage.png usemap ="#clickMap">";
    html += "<map id =\"clickMap\" name=\"clickMap\">
    <area shape =\"rect\" coords =\"0,0,82,126\" href ="+ newLink +" alt=\"Quiz\" />
    </map>"

            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = html ;
            msg.IsBodyHtml = isBodyHtml;
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

**UPDATE **

string html = "<h1>Quiz!</h1><img src='" + src + "' usemap ='#clickMap'>";
            html += "<map id =\"clickMap\" name=\"clickMap\">" +
                     "<area shape =\"rect\" coords =\"0,0,82,126\" href =" + quickLink + "alt=\"Quiz\" title='Click For Quiz'/></map>";
Community
  • 1
  • 1
Anand
  • 14,545
  • 8
  • 32
  • 44
0

Add in you message Body

<a href="Default.aspx" > <img alt="abc" src='"+ imageURl +"' /></a>

Satinder singh
  • 10,100
  • 16
  • 60
  • 102
0

I would suggest to use MailMessage.AlternateViews to get the attachment collection used to store alternate forms of the message body.

Example you can just send plain text message and or html formatted message with the image in it

HatSoft
  • 11,077
  • 3
  • 28
  • 43