Solved

C# ASP.Net system.net.mail: How to Pass in Variable and Send Mail??

Posted on 2008-10-18
3
894 Views
Last Modified: 2013-12-17
Hello,
I am trying to use System.Net.Mail to send an email notification from a web page and have run into a couple road blocks.  Any help would be appreciated!

What I am trying to do:
I am creating a web project that allows users to upload and download files.  I want an email notification to be sent to the administrator when a file has been downloaded and an email notification to be sent to the user when a file has been uploaded for them.

I am completely stuck.  I am very new to development and in addition to simply making System.Net.Mail work, I am finding that I am having trouble figuring out how to pass the variables from my aspx page to my class page.  In particular, you can see that I am having trouble grabbing the user name from the aspx page...to get it there I would use:

string UserName = User.Identity.Name;

But I don't know how to move it.

Finally, once I do have everything passed correctly, I am really not sure how to call this from the code behind.  I have read a lot of examples (including: http://forums.asp.net/t/971802.aspx?PageIndex=1) but I have to use the format below and I am lost.

I included all the code that I thought relevant.

Thanks for the help!
AJ
MailMessage.cs:
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Text;
 
namespace FileTransfer2
{
    public class SendMailMessage
    {
        private int _fileID;
        private string _UserName; //do the same thing with username
 
        public SendMailMessage(int fileID, string _UserName)
        {
            _fileID = fileID;
            _UserName = UserName; //this has to be passed in from the code behind
        }
 
        public void DownloadSendMessage(int fileid, string ToAddress, string action)
        {
            
           
            ClientFileRepository repository = new ClientFileRepository();
            DataTable FilebyID = repository.GetFileInfo(fileid);
 
            string FileName;
            string FilePath;
            string UserName =  ; //incomplete
             
            if (FilebyID != null && FilebyID.Rows.Count > 0)
             {
                FileName = FilebyID.Rows[0]["FileName"].ToString();
                FilePath = FilebyID.Rows[0]["ClientFile"].ToString();
             }
            
         
            string from = ConfigurationManager.AppSettings["AdminEmailAddress"];
            string subject = string.Format("File {0} was {3}ed by {1} at {2:MM/dd/yy}",
               FilePath, userName, DateTime.Today, action);
            
            StringBuilder body = new StringBuilder();
            body.AppendLine("A file was downloaded");
            body.AppendLine();
            body.AppendLine();
            body.AppendFormat("UserName: {0}\n", userName);
            body.AppendFormat("FileName: {0}\n", FileName);
 
 
            MailMessage DownloadMessage = new MailMessage(from, ToAddress, subject, body.ToString());
            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.Send(DownloadMessage);
        }   
 
    }
}
 
 
ClientFileRepository.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
 
namespace FileTransfer2
{
    public class ClientFileRepository
    {
 
        public int InsertNewFile(string fileName, string description, string clientfile)
        {
            int result = 0;  
            try
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("InsertNewFile", conn)) 
                    {
 
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@FileName", fileName);
                        cmd.Parameters.AddWithValue("@Description", description);
                        cmd.Parameters.AddWithValue("@ClientFile", clientfile);
                        conn.Open();
                        result = int.Parse(cmd.ExecuteScalar().ToString()); 
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
 
            return result;
        }
 
 
        public DataTable GetFileInfo(int id)
        {
            try
            {
 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("getFilebyFileID", conn)) 
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Id", id);
 
                        SqlDataAdapter daFilesbyId = new SqlDataAdapter(cmd);
                        DataTable FilesbyId = new DataTable();
                        conn.Open();
                        daFilesbyId.Fill(FilesbyId);
                        return FilesbyId;
                    }
                }
            }
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
 
        }
 
        public DataTable GetUserGuid(string UserName)
        {
            try
            {
 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("getUserID", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@UserName", UserName);
 
                        SqlDataAdapter daGetUserGuid = new SqlDataAdapter(cmd);
                        DataTable UserGuid = new DataTable();
                        conn.Open();
                        daGetUserGuid.Fill(UserGuid);
                        return UserGuid;
                    }
                }
            }
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
        }
 
        public void InsertUser_ClientFile(Guid guid, int fileid)
        {
            try
            {
 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("InsertUser_ClientFile", conn)) 
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@userguid", guid);
                        cmd.Parameters.AddWithValue("@fileid", fileid);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
        }
 
        public void UpdateESign(int id, string eSignUserName)
        {
            try
            {
 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("updateESign", conn)) 
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@id", id);
                        cmd.Parameters.AddWithValue("@eSignUserName", eSignUserName);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
 
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
        }
    }
}
 
 
ViewClientFilebyDateRange.aspx:
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FileTransfer2.DataSets;
using System.Net.Mail;
 
namespace FileTransfer2
{
    public partial class ViewClientFilesbyDateRange : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ObjectDataSource1.SelectParameters["UserName"].DefaultValue = this.User.Identity.Name;
            ObjectDataSource1.SelectParameters["startDate"].ConvertEmptyStringToNull = true;
            ObjectDataSource1.SelectParameters["endDate"].ConvertEmptyStringToNull = true;
 
            if (!Page.IsPostBack)
            {
                ObjectDataSource1.SelectParameters["startDate"].DefaultValue = string.Empty;
                ObjectDataSource1.SelectParameters["endDate"].DefaultValue = string.Empty;
                GridView1.DataBind(); 
            }
 
        }
 
        protected void btnSubmitDates_Click(object sender, EventArgs e)
        {
            ObjectDataSource1.SelectParameters["startDate"].DefaultValue = this.txtStartDate.Text.Trim();
            ObjectDataSource1.SelectParameters["endDate"].DefaultValue = this.txtEndDate.Text.Trim();
            GridView1.DataBind();
        }
 
        protected void GridView1_RowDatabound(object sender, GridViewRowEventArgs e)
        {
 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                
                HyperLink download = ((HyperLink)e.Row.FindControl("HyperLink1"));
                DataRowView row = (DataRowView)e.Row.DataItem;
                download.NavigateUrl = String.Format("DownloadFile.aspx?ID={0}", row["ID"]);
 
                HyperLink sign = ((HyperLink)e.Row.FindControl("HyperLink2"));
                sign.NavigateUrl = String.Format("eSign.aspx?ID={0}", row["ID"]);
 
            }
        }
 
 
        protected void btnUploadFile_Click(object sender, EventArgs e)
        {
            Response.Redirect("FileUpload.aspx");
         
        }
 
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
          
            int rowIndex = Convert.ToInt32(e.CommandArgument); //CommandArgument passed in row ID (not file ID)
            
            int clientFileID = (int)GridView1.DataKeys[rowIndex].Values[0]; 
            
            switch (e.CommandName)
            {
                case "Download": //named the CommandName "Download" in the grid props
                    DownloadFile(clientFileID);
                    break;
                default:
                    break;
            } 
        }
 
        private void DownloadFile(int clientFileID)
        {
            SendDownloadNotificaitonEmail(clientFileID); //stuck here, I need to send a UserName too, is this the right place??
 
            HelperFunctions.TransmitFile(clientFileID);
           
        }
 
        private void SendDownloadNotificaitonEmail(int clientFileID) //stuck here, do I need both?
        {
 
        }
 
 
   }
 
    
}
 
 
HelperFunctions.cs:
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
namespace FileTransfer2
{
    public static class HelperFunctions
    {
        public static void TransmitFile(int id)
        {
            try
            {
 
                 HttpResponse Response = HttpContext.Current.Response; //makes Response available
                
                ClientFileRepository repository = new ClientFileRepository();
                DataTable FilebyID = repository.GetFileInfo(id);
                if (FilebyID != null && FilebyID.Rows.Count > 0)
                {
                    string FileName = FilebyID.Rows[0]["FileName"].ToString();
                    string FilePath = FilebyID.Rows[0]["ClientFile"].ToString();
                    string FileExtension = System.IO.Path.GetExtension(FilePath);
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
                    Response.ContentType = (FileExtension);
                    Response.TransmitFile(FilePath);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
 
                }
            }
 
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
 
        }
    }
}
 
Web.config: (just the app settings part)
 
<configuration>
 
	<appSettings>
		<add key="UploadDirectory" value="c:\Uploads\" />
		<add key ="AdminEmailAddress" value="validaddress@validdomain.com" />
	   </appSettings>

Open in new window

0
Comment
Question by:AJ0424
3 Comments
 
LVL 1

Expert Comment

by:hakkekushou
ID: 22752851
Pass the username from the page instead of initializing its value in your class.
0
 

Author Comment

by:AJ0424
ID: 22752993
Thank you but that was the first part of what I was asking how to do.  I think I may have figured out how to pass it from the aspx page but I am not sure yet because I am still trying to determine how to call the method from the aspx page.  My changes are below.

Thanks,
AJ

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Text;
 
namespace TestProject
{
    public class SendMailMessage
    {
        private int _fileID;
        private string _UserName; 
 
        public SendMailMessage(int fileID, string _UserName)
        {
            _fileID = fileID;
            _UserName = HttpContext.Current.Session["UserName"].ToString(); //this is how I am trying to pass the current username from the aspx page
        }
 
 
        public void DownloadSendMessage(int fileid, string ToAddress, string action)
        {
 
 
            ClientFileRepository repository = new ClientFileRepository();
            DataTable FilebyID = repository.GetFileInfo(fileid);
 
            string FileName = null;
            string FilePath = null;
            string UserName = _UserName; //incomplete
 
            if (FilebyID != null && FilebyID.Rows.Count > 0)
            {
                FileName = FilebyID.Rows[0]["FileName"].ToString();
                FilePath = FilebyID.Rows[0]["ClientFile"].ToString();
            }
 
            string from = ConfigurationManager.AppSettings["AdminEmailAddress"];
            string subject = string.Format("File {0} was downloaded by {1} at {2:MM/dd/yy}",
                FilePath, UserName, DateTime.Today);
 
            //string subject = string.Format("File {0} was {3}ed by {1} at {2:MM/dd/yy}",
            //   FilePath, UserName, DateTime.Today, action); //action will = upload or download, need to pass it in somehow
 
            StringBuilder body = new StringBuilder();
            body.AppendLine("A file was downloaded");
            body.AppendLine();
            body.AppendLine();
            body.AppendFormat("UserName: {0}\n", UserName);
            body.AppendFormat("FileName: {0}\n", FileName);
 
 
            MailMessage DownloadMessage = new MailMessage(from, ToAddress, subject, body.ToString());
            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.Send(DownloadMessage);
        }   
 
 
    }
}
 
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FileTransfer2.DataSets;
using System.Net.Mail;
 
namespace TestProject
{
    public partial class ViewClientFilesbyDateRange : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ObjectDataSource1.SelectParameters["UserName"].DefaultValue = this.User.Identity.Name;
            ObjectDataSource1.SelectParameters["startDate"].ConvertEmptyStringToNull = true;
            ObjectDataSource1.SelectParameters["endDate"].ConvertEmptyStringToNull = true;
 
            if (!Page.IsPostBack)
            {
                ObjectDataSource1.SelectParameters["startDate"].DefaultValue = string.Empty;
                ObjectDataSource1.SelectParameters["endDate"].DefaultValue = string.Empty;
                GridView1.DataBind(); 
            }
 
            Session["UserName"] = User.Identity.Name;
            //Response.Write(Session["UserName"]); //verifying UserName
 
 
        }
 
        protected void btnSubmitDates_Click(object sender, EventArgs e)
        {
            ObjectDataSource1.SelectParameters["startDate"].DefaultValue = this.txtStartDate.Text.Trim();
            ObjectDataSource1.SelectParameters["endDate"].DefaultValue = this.txtEndDate.Text.Trim();
            GridView1.DataBind();
        }
 
        protected void GridView1_RowDatabound(object sender, GridViewRowEventArgs e)
        {
 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                
                HyperLink download = ((HyperLink)e.Row.FindControl("HyperLink1"));
                DataRowView row = (DataRowView)e.Row.DataItem;
                download.NavigateUrl = String.Format("DownloadFile.aspx?ID={0}", row["ID"]);
 
                HyperLink sign = ((HyperLink)e.Row.FindControl("HyperLink2"));
                sign.NavigateUrl = String.Format("eSign.aspx?ID={0}", row["ID"]);
 
            }
        }
 
 
        protected void btnUploadFile_Click(object sender, EventArgs e)
        {
            Response.Redirect("FileUpload.aspx");
         
        }
 
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
          
 
            int rowIndex = Convert.ToInt32(e.CommandArgument); 
            
            int clientFileID = (int)GridView1.DataKeys[rowIndex].Values[0]; 
                        
            switch (e.CommandName)
            {
                case "Download": 
                    DownloadFile(clientFileID);
                    break;
                default:
                    break;
            } 
        }
 
        private void DownloadFile(int clientFileID)
        {
            SendDownloadNotificaitonEmail(clientFileID); 
 
            HelperFunctions.TransmitFile(clientFileID);
           
        }
 
        private void SendDownloadNotificaitonEmail(int clientFileID) 
        {
            //stuck here
        }
        
 
   }
 
    
}
 
 
 
    public static class HelperFunctions
    {
        public static void TransmitFile(int id)
        {
            try
            {
 
                HttpResponse Response = HttpContext.Current.Response; 
                
                ClientFileRepository repository = new ClientFileRepository();
                DataTable FilebyID = repository.GetFileInfo(id);
                if (FilebyID != null && FilebyID.Rows.Count > 0)
                {
                    string FileName = FilebyID.Rows[0]["FileName"].ToString();
                    string FilePath = FilebyID.Rows[0]["ClientFile"].ToString();
                    string FileExtension = System.IO.Path.GetExtension(FilePath);
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
                    Response.ContentType = (FileExtension);
                    Response.TransmitFile(FilePath);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
 
                }
            }
 
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
 
        }
    }
 
 
 
public class ClientFileRepository
    {
 
        public DataTable GetFileInfo(int id)
        {
            try
            {
 
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("getFilebyFileID", conn)) //stored proc name
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Id", id);
 
                        SqlDataAdapter daFilesbyId = new SqlDataAdapter(cmd);
                        DataTable FilesbyId = new DataTable();
                        conn.Open();
                        daFilesbyId.Fill(FilesbyId);
                        return FilesbyId;
                    }
                }
            }
            catch (SqlException ex)
            {
 
                throw ex;
            }
 
 
        }
 
 
<configuration>
 
	<appSettings>
		<add key ="AdminEmailAddress" value="validEmailAddress@validDomain.com" />
	   </appSettings>

Open in new window

0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
ID: 22757616

private void SendDownloadNotificaitonEmail(int clientFileID) 
{
      // assign ToAddress, then
      SendMailMessage smm = new SendMailMessage();
      smm.DownloadSendMessage(clientFileID, ToAddress, "download");
      
}

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question