Sie sind auf Seite 1von 5

private void Page_Load(object sender, System.EventArgs e) { MailMessage mail = new MailMessage(); mail.To = "me@mycompany.com"; mail.From = "you@yourcompany.com"; mail.

Subject = "this is a test email."; mail.Body = "Some text goes here"; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "my_username_here"); //set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "super_secret"); //set your password here SmtpMail.SmtpServer = "mail.mycompany.com"; //your real server goes here SmtpMail.Send( mail ); }

I wrote an article in May 2005 on how to send e-mail via ASP.NET v2.0. This is a quick follow-up to that article with additional information specifically addressing the issue of SMTP-Authentication against a remote mail server. Many web hosts now have their servers "locked down" and require a username and password to send e-mail from their servers. If you have code that uses "localhost" (the SMTP service running on the local machine) then this should not be an issue, but if you have a situation where you need to relay e-mail off a remote mail server that is secured, this article should help you. The real work is done by the NetworkCredential object. According to MSDN, this object "provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication." The benefit of making this a two-step process rather than passing username and password to the .Credentials property of the SmtpClient object is not clear, but that is what is required. Here is a fully working quick code sample that you can use to get started on your own SMTP-Auth supporting e-mail code.
'Create a new MailMessage object and specify the"From" and "To" addresses Dim Email As New System.Net.Mail.MailMessage( _ "Brad.Kingsley@orcsweb.com", "Brad@KingsleyTeam.com") Email.Subject = "test subject" Email.Body = "this is a test" Dim mailClient As New System.Net.Mail.SmtpClient() 'This object stores the authentication values Dim basicAuthenticationInfo As _ New System.Net.NetworkCredential("username", "password") 'Put your own, or your ISPs, mail server name onthis next line mailClient.Host = "Mail.RemoteMailServer.com" mailClient.UseDefaultCredentials = False mailClient.Credentials = basicAuthenticationInfo mailClient.Send(Email)

We had a Microsoft exchange server 2003 running and for the life of me i couldn't figure out why it was kicking back my emails. This worked like a charm for passing the authentication for relay.

Title: Help Required Name: Anand Dave Date: 2/17/2011 1:46:06 AM Comment:
Hi Code Given Below Run successfully but i don't get email in my mail box Plz Help me oout..... SmtpClient smtpClient = new SmtpClient(); MailMessage message = new MailMessage(); MailAddress fromAddress = new MailAddress("From Email Address", "Name"); smtpClient.Host = "smtp.mail.yahoo.com"; smtpClient.Credentials = new NetworkCredential("from email address", "pwd"); smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; smtpClient.Port = 465; message.From = fromAddress; message.To.Add("my yahoo address"); message.Subject = "Feedback22"; message.IsBodyHtml = false; message.Body = "Hi Test2 for Email";

smtpClient.Send(message); lblStatus.Text = "Email successfully sent."; lblStatus.Text = "Send Email Failed." + ex.Message;

Login to an SMTP server and send an email


There are many articles on how to send authenticated email in ASP.NET 2.0, but here's how to send an email using a SMTP server that requires authentication.

Collapse | Copy Code


(Imports System.Net) Dim client As New SmtpClient("smtp.server.com") 'your SMTP server client.UseDefaultCredentials = False 'Your username and password to login client.Credentials = New Net.NetworkCredential("username", "password") client.DeliveryMethod = SmtpDeliveryMethod.Network Dim Mail As New MailMessage("from@email.com", "to@email.com", _ "This is my subject", _ "This is my pretty, yet boring and useless message") Mail.IsBodyHtml = True Try client.Send(Mail) Catch ex As Exception Response.Write(ex.Message) 'Write error message Exit Sub End Try 'successful

6.3.5. Checking Authentication and identifying roles The most important part of implementing security is to ensure that on each request, the application verifies the authentication and resolves the user role. For this purpose, we make use of the following global application level events:

WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e) Application_AuthenticateRequest(Object sender, EventArgs e)

These events are raised automatically on each request.

WindowsAuthentication_OnAuthenticate is raised first. In the corresponding


method, we implement the following logic:

1. Check whether authenticationCookie for the application exists. If so,


return from the method. If it does not exist, continue with the next steps.

2. Extract the AD-user name sent by IIS. It is available in the event argument
as e.Identity.Name. 3. Query the database for application-roles against this user-name. 4. Create a Forms Authentication ticket and embed a string of user roles in it. 5. Create a new applicationauthenticationCookie and store the encrypted Forms Authentication ticket in it. Inside the method for the Application_AuthenticateRequest event, do the following.

1. Read applicationauthenticationCookie and re-create the Forms


Authentication ticket.

2. Read the user roles from the Forms Authentication ticket and create an object 3.
of the Principal object which contains these user-roles. Store this Principal object in HttpContext.Current.User.

The following code shows the implementation of these tasks:


Collapse | Copy Code

protected void WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e) { if(Request.Cookies.Get("authCookie") != null) return; string strUserIdentity; string strUserRoles; FormsAuthenticationTicket formsAuthTicket; HttpCookie httpCook; String strEncryptedTicket; strUserIdentity = e.Identity.Name; strUserRoles = GetUserRoles(strUserIdentity); // "MD|CST|AM" from DB

formsAuthTicket = new FormsAuthenticationTicket(1, strUserIdentity, DateTime.Now, DateTime.Now.AddMinutes(60), false, strUserRoles); strEncryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket); httpCook = new HttpCookie("authCookie", strEncryptedTicket); Response.Cookies.Add(httpCook); } protected void Application_AuthenticateRequest(Object sender, EventArgs e) { FormsAuthenticationTicket formsAuthTicket; HttpCookie httpCook; GenericIdentity objGenericIdentity; myAppPrincipal objMyAppPrincipal; string[] strRoles; httpCook = Context.Request.Cookies.Get("authCookie"); formsAuthTicket = FormsAuthentication.Decrypt(httpCook.Value); objGenericIdentity = new GenericIdentity(formsAuthTicket.Name); strRoles = formsAuthTicket.UserData.Split('|'); objMyAppPrincipal = new myAppPrincipal(objGenericIdentity, strRoles); HttpContext.Current.User = objMyAppPrincipal; }

6.3.6. Checking role based Authorization On the Page_Load of each web page, check whether the user current-role available inHttpContext.Current.User is allowed to access the page. If not, then redirect to a common page showing the message You are not authorized to view this page.

7. Summary
Providing application security is an important aspect of ensuring information security. Authentication helps to verify that the user is, in fact, who the user claims to be. The application obtains credentials (various forms of identification, such as name and password) from a user and validates those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Authorization limits access rights by granting or denying specific permissions to an authenticated identity. ASP.NET uses Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access. In ASP.NET, Windows Authentication can be used along with either Windows role based authorization or Custom authorization. In Windows role based authorization, access to the application folder for Windows users/groups is granted/denied as per the setting in web.config. Whereas in custom authorization, this logic is implemented programmatically.

Das könnte Ihnen auch gefallen