1

我是一名新的 ASP.NET 开发人员,我正在开发一个培训管理系统,该系统将每周向我部门的员工发送电子邮件通知,以参加每周一次的短期培训测验。一切正常。对于发送电子邮件通知,我当然使用的是 C# Mail 功能。该电子邮件是基于文本的电子邮件,每周都会包含指向新测验的链接。

现在,我想将此基于文本的电子邮件作为基于图像的电子邮件。该图像中有一个特定部分将作为新测验的链接。所以每周都会在图片的那部分下有一个新的链接。我在这部分苦苦挣扎,我不知道如何修改我的 C# Mail 函数来处理它。这是我第一次使用C# Mail function. 我在谷歌上搜索了很多,我很困惑。仅供参考,我设计了我的邮件功能来处理将相同的电子邮件发送给 200 多个用户,方法是将它们分成 10 个用户的列表,如下所示。

您能帮我修改下面显示的代码以处理发送该图像吗?让我们假设我们有任何图像。

C#代码:

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();
        }
    }

更新:

伙计们,你们没有明白我的意思。整个电子邮件将是一个图像,并且该图像的小部分(如小圆圈)将作为超链接而不是整个图像。而那个链接我们每周都会更改,比如default.aspx/testid=12等等。那么该怎么做呢?

更新#2: 我更新了代码的以下部分以包含图像,但我在添加 AlternateViews.ADD(av) 时遇到了问题。如何解决这个问题?

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);

更新#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();
        }
    }
4

3 回答 3

2

您必须将图像作为 HTML 的一部分发送。使用以下代码

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

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

我从这些链接中获得了帮助。希望对您也有帮助

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

  2. 发送带有 HTML 文件作为正文的电子邮件 (C#)

更新

将您的测验 URL 存储在数据库中,以便每周更改使用图像映射创建可点击的图像的一部分。如下构建html。

//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>"

更新 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;
        }

    }

**更新 **

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>";
于 2012-07-28T06:30:30.733 回答
0

添加你的消息正文

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

于 2012-07-28T06:31:18.883 回答
0

我建议使用MailMessage.AlternateViews来获取用于存储邮件正文替代形式的附件集合。

例如,您可以只发送带有图像的纯文本消息和/或 html 格式的消息

于 2012-07-28T06:38:37.053 回答