[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
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
Medium Priority
?
1,129 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 2000 total points
ID: 34201095
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
ID: 34201324
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
ID: 34201401
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
Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

 

Author Comment

by:newjeep19
ID: 34201473
No I am still learning C#
0
 

Author Comment

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

Author Comment

by:newjeep19
ID: 34202366
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
ID: 34207077
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
ID: 34207518
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
ID: 34207579
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

A hard and fast method for reducing Active Directory Administrators members.
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.
Suggested Courses

649 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