Solved

Active Directory get the email and add it to my c# email form field to send an email from my asp.net webpage

Posted on 2010-11-23
9
868 Views
Last Modified: 2012-05-10
What is the syntax for getting the currently loged on user email address through Active Directory using C# and then taking that email address and inserting it into the from field in my email submit property
Ex:
otected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {

                // create mail message object
                MailMessage mail = new MailMessage();

                mail.From = new MailAddress(txtNewFrom.Text); - email address of person logged in from AD
                mail.To.Add("me@company.com");                      // put To: address here
                // mail.CC = this.ddlManagerApprov.Items;             // put CC: address here
                mail.Subject = "IT Account Request Form";            // put subject here      
                mail.Body = TextBox9.Text;                          // put body of email here

                // put smtp server you will use here
                SmtpClient smtp = new SmtpClient("ip address"); //SmtpClient
                smtp.Send(mail);
                Label1.Text = "Thank the email was to IT. Your supervior was CC'd for approval.  ";
            }

            catch
            {
                Label1.Text = " Email was not sent";
            }
0
Comment
Question by:newjeep19
  • 5
  • 4
9 Comments
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
Comment Utility
Normally the user-name is the email address, so this might work:

string userName = Request.LogonUserIdentity.Name.Split('\\')[1];
string email = userName + "@domain.com";

Open in new window


Otherwise, you can add a reference to System.DirectoryServices and search the Active Directory (assuming your web app is running as a user with sufficient permissions to query the directory, mine is running as NetworkService).
string email = String.Empty;
string userName = Request.LogonUserIdentity.Name.Split('\\')[1];
string ldapFilter = String.Format("(&(objectCategory=user)(sAMAccountName={0}))", userName);
DirectorySearcher searcher = new DirectorySearcher(ldapFilter, new string[] { "mail" }, SearchScope.Subtree);
SearchResult result = searcher.FindOne();
if (result != null)
{
	email = (string)result.GetDirectoryEntry().Properties["mail"].Value;
}

Open in new window

0
 

Author Comment

by:newjeep19
Comment Utility
I am confused on how this inserts the current / logged on user email into the script listed to submit the email....please explain
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
It doesn't, just demonstrates how to obtain the current users email address. It's just a partial code snippet - you'll need to adapt it for your project.

I can help more later, when I get in front of a computer, if you still need it.

Are you already familiar with the concept of methods, and use of strings in C#?
0
 

Author Comment

by:newjeep19
Comment Utility
No I am still learning C#
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:newjeep19
Comment Utility
I would still need some more help with this question.........thanks
0
 

Author Comment

by:newjeep19
Comment Utility
How would I take the the user email address capture it and insert it into the form field in the C# sysntax in the code above......thanks
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
You might want to get a strong grasp on the basics before attempting this slightly more advanced task, perhaps start with a book on C#. ;)

First, a quick lesson on methods...basically a method (or function) is a block of code that belongs to a class, it can optionally take parameters, performs some work, and can optionally return a value.  You "call" (use) a method by writing it's name followed by parentheses (if the method takes parameters you would provide them inside the parentheses).

For example, you might use a method that shuts down the computer, which does not need any parameters and doesn't need to return a value:
ShutdownComputer();

Open in new window


However, if you use a method that adds two int's and returns the result of the addition. In this case, the method would take two int's as parameters and returns the result of the addition.
int numberOne = 3;
int numberTwo = 2;

// This line calls the Add() method,
// and passes in the two int's as parameters.
// The Add() method returns an int, so we can
// use this syntax to assign the result
// of the Add() method to a variable
int result = Add(numberOne, numberTwo);

Open in new window


When you create your own classes you can add your own methods to those classes. When you create an ASP.Net page, you actually are creating your own class - and in fact you have already added your own method to that class, which is btnSend_Click() (it doesn't return any value, and takes two parameters - an "object" and an "EventArgs").

If you can add a method to your page, "GetEmailAddress" for example, that returns a string (using the second method I posted in my original response) you can use that method to assign the users email address to a string variable. You would need to check the result of that function to make sure it's not null (i.e. in the case the user doesn't have an e-mail address), and then assign that string variable to the "To" property of your MailMessage.

Here's a simple web page that demonstrates adding a method that takes a parameter and returns a value:
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
	protected void SubmitButton_Click(object sender, EventArgs e)
	{
		ListItem selectedItem = CategoryRadioButtonList.SelectedItem;

		if (selectedItem == null)
			ResultsLabel.Text = "No Category Selected";
		else
			ResultsLabel.Text = GetCategoryItem(selectedItem.Text);
	}

	private string GetCategoryItem(string Category)
	{
		if (Category == "Animal")
			return "Zebra";
		else if (Category == "Color")
			return "Purple";
		else if (Category == "Vehicle")
			return "Airplane";
		else
			return "Invalid Category";
	}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:RadioButtonList ID="CategoryRadioButtonList" runat="server">
			<asp:ListItem Text="Animal" />
			<asp:ListItem Text="Color" />
			<asp:ListItem Text="Vehicle" />
		</asp:RadioButtonList>
		<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
		<hr />
		<asp:Label ID="ResultsLabel" runat="server" text="Select a category and click Submit." />
    </div>
    </form>
</body>
</html>

Open in new window

0
 

Author Comment

by:newjeep19
Comment Utility
Thank's I understand the class and method so..... in your first example I would insert
email = (string)result.GetDirectoryEntry().Properties["mail"].Value;
into:  mail.From = new MailAddress("mail");
under: btnSend()_Click()
  try

            {

            // create mail message object
            MailMessage mail = new MailMessage();

            string email = String.Empty;
            string userName = Request.LogonUserIdentity.Name.Split('\\')[1];
            string ldapFilter = String.Format("(&(objectCategory=user)(sAMAccountName={0}))", userName);
            DirectorySearcher searcher = new DirectorySearcher(ldapFilter, new string[] { "mail" }, SearchScope.Subtree);
            SearchResult result = searcher.FindOne();
            if (result != null)
            {
                email = (string)result.GetDirectoryEntry().Properties["mail"].Value;
            }
Correct......?
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
You got it.  The only thing I would do different is make a seperate method to retrieve the email address.  If the user can't be found in the Active Directory for some reason, or the user doesn't have an e-mail address, the method could return null.  This way, in your btnSend_Click, you can call the "get-email" method and check the value it returns - if the value it returned is null, display a message to the user, otherwise you can use the value as the sender's address.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.DirectoryServices" %>
<%@ Import Namespace="System.Net.Mail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
	protected void SendButton_Click(object sender, EventArgs e)
	{
		// Declare a string variable to hold senders email
		// and assign it the return value of the GetADUserMail() method
		string senderAddress = GetADUserMail();
		
		// If sender is null, then user not found or has no email address
		if (senderAddress == null)
		{
			ResultsLabel.Text = "Your user account was not found, or you have no email address - message not sent.";
			return;
		}

		try
		{
			MailMessage mail = new MailMessage();
			mail.From = new MailAddress(senderAddress);
			mail.To.Add(ToTextBox.Text);
			mail.Subject = SubjectTextBox.Text;
			mail.Body = BodyTextBox.Text;

			SmtpClient smtp = new SmtpClient("your.smtp.server.com");
			smtp.Send(mail);

			ResultsLabel.Text = "Your message was successfully sent.";
		}
		catch (Exception ex)
		{
			ResultsLabel.Text = "An error occurred sending your e-mail, the error is:\r\n" + ex.Message;
		}
	}

	private string GetADUserMail()
	{
		// Get the username in the form "DOMAIN\user"
		string fullUserName = Request.LogonUserIdentity.Name;
		
		// Use the .Split() method to break up the full name
		// into an array of strings, where the first item (item 0) in the
		// array is the domain name, and the second item (item 1) is
		// the user name
		string[] userNameParts = fullUserName.Split('\\');
		
		// Create an ActiveDirectorySearcher object
		DirectorySearcher searcher = new DirectorySearcher();
		
		// Assign the active directory LDAP search filter
		searcher.Filter = "(&(objectClass=person)(sAMAccountName=" + userNameParts[1] + "))";
		
		// Set the search to search entire tree
		searcher.SearchScope = SearchScope.Subtree;
		
		// Get the result of the search
		SearchResult result = searcher.FindOne();
		
		// If result is null no matches found, so this
		// method can return null to indicate no email
		// address found
		if (result == null)
			return null;
		
		// Get the directory entry found by the search
		DirectoryEntry entry = result.GetDirectoryEntry();
		
		// Check if the "mail" property of this entry is null
		// and return null if no email address
		if (entry.Properties["mail"].Value == null)
			return null;
		else // Otherwise return the email address
			return entry.Properties["mail"].Value.ToString();
	}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		To: <asp:TextBox id="ToTextBox" runat="server" /><br />
		Subject: <asp:TextBox ID="SubjectTextBox" runat="server" /><br />
		Message:<br />
		<asp:TextBox ID="BodyTextBox" runat="server" TextMode="MultiLine" Rows="10" /><br />
		<asp:Button ID="SendButton" runat="server" Text="Send" OnClick="SendButton_Click" />
		<hr />
		Result: <asp:Label ID="ResultsLabel" runat="server" />
    </div>
    </form>
</body>
</html>

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
This video teaches users how to migrate an existing Wordpress website to a new domain.

728 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now