Digital Colony!

Sending Email in ASP.NET 2.0 (C#)

Here is the C# version of Sending Email in ASP.NET 2.0 (VB.NET).
using System.Net.Mail;
The code snippet demonstrates Larry King emailing Oprah.
MailMessage Message = new MailMessage();
SmtpClient Smtp = new SmtpClient();
// Build message
Message.From = new MailAddress("larryking@cnn.com", "Larry King");
Message.To.Add(new MailAddress("oprah@oprah.com", "Oprah"));
Message.IsBodyHtml = false;
Message.Subject = "Come on My Show Soon";
Message.Body = "Please be a guest on my show. - Larry";
// Send Message
// each web host is different 
// (adjust next 2 lines accordingly)
Smtp.Host = "localhost";
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.Send(Message);

Labels: , ,

 

Sending Email in ASP.NET Using SMTP Authentication (VB.NET)

If you don't need to use Authentication to send email, check out the code snippet Sending Email in ASP.NET 2.0 (VB.NET). If your web host requires that you use SMTP Authentication, some additional lines of code will need to be added.
Dim Message As MailMessage = New MailMessage()
Dim Smtp As New SmtpClient()
Dim SmtpUser As New System.Net.NetworkCredential()
'-- Build Message
Message.From = New MailAddress("larryking@cnn.com", "Larry King")
Message.To.Add(New MailAddress("oprah@oprah.com", "Oprah"))
Message.IsBodyHtml = False
Message.Subject = "Come on My Show Soon"
Message.Body = "Please be a guest on my show. - Larry"
'-- Define Authenticated User
SmtpUser.UserName = "larryking"
SmtpUser.Password = "suspenders"
SmtpUser.Domain = "mail.cnn.com"
'-- Send Message
Smtp.UseDefaultCredentials = False
Smtp.Credentials = SmtpUser
Smtp.Host = "mail.cnn.com"
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp.Send(Message)

Labels: ,

 

Sending Email in ASP.NET 2.0 (VB.NET)

Way back in 2001, I wrote ASP.NET Email Using VB for ASP.NET 1.x. ASP.NET 2.0 now uses the System.Net.Mail instead of the System.Web.Mail Namespace.

Here is a quick snippet to get you started.
Dim Message As MailMessage = New MailMessage()
Dim Smtp As New SmtpClient()
'-- Build Message
Message.From = New MailAddress("larryking@cnn.com", "Larry King")
Message.To.Add(New MailAddress("oprah@oprah.com", "Oprah"))
Message.IsBodyHtml = False
Message.Subject = "Come on My Show Soon"
Message.Body = "Please be a guest on my show. - Larry"
'-- Send Message
'-- each web host is different 
'-- (adjust next 2 lines accordingly)
Smtp.Host = "localhost"
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp.Send(Message)
If your web host requires that you send the email using SMTP Authentication read Sending Email in ASP.NET Using SMTP Authentication (VB.NET).

Labels: , ,

 

Masking Email Addresses in PHP

Steve Waag from Lacanche Ranges was able to translate the ASP in Masking Your Email Address to PHP.
<?php
function maskEmail($email) {
  $maskedEmail = '';
  for ($j = 0; $j < strlen($email); $j++) {
    $maskedEmail .= '&#' . ord(substr($email, $j, 1)) . ';' ;
  }
  $emailHtml = '<a href="m&#' . ord('a') . ';&#' . ord('i') . ';&#' . ord('l')
    . ';&#' . ord('t') . ';o:' . $maskedEmail . '">' . $maskedEmail . '</a>';
  return $emailHtml;
}
?>

<p>For more information email me at
  <?php echo maskEmail('someEmail@someDomain.net') ?>.</p>

Labels: , ,

 

Mask Email ASCII Control for ASP.NET

In the article Masking Your Email Address, we went over why you would want to hide your email address inside the source code of an HTML document, but still make it visible to the human readers of that page.

Encapsulating the code into a single .NET user control is ideal for protecting email addresses for ASP.NET sites.

Step 1 - Create a Web User Control

Add an asp:Literal control to that page.
<asp:Literal ID="ltEmail" runat="server" />

Step 2 - Jump to the Code Behind

The EmailMask code follows. Note the name of the class lab_maskemail_EmailMask was created by Visual Studio for me. Use whatever name you like or Visual Studio recommends here. The rest of the code should be the same. This code is for ASP.NET 2.0.
using System;
using System.Text;
using System.Web;

public partial class lab_maskemail_EmailMask : System.Web.UI.UserControl
{
    private string emailAddress;
    public string EmailAddress
    {
        get { return emailAddress; }
        set { emailAddress = value; } 
    }

    private string visibleAddress;
    public string VisibleAddress
    {
        get 
        {
            // if unassigned return emailAddress
            if (visibleAddress==null || visibleAddress.Length == 0)
            {
                return emailAddress;
            }
            else
            {
                return visibleAddress; 
            }
            
       }
        set { visibleAddress = value; }
    }

    private string mouseoverTag;
    public string MouseoverTag
    {
        get { return mouseoverTag; }
        set { mouseoverTag = value; }
    }

    private string subject;
    public string Subject
    {
        get { return subject; }
        set { subject = value; }
    }

    private string cssClass;
    public string CssClass
    {
        get { return cssClass;}
        set { cssClass = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // The MIN required for control is an email address, confirm it exists
        if (emailAddress == null || emailAddress.Length == 0)
        {
            ltEmail.Text = "Assign EmailAddress to Control";
            return;
        }

        // Build ASCII encoded Link
        StringBuilder asciiLink = new StringBuilder();
        asciiLink.Append("<a href=\"m&#97;ilto:");
        asciiLink.Append(ASCIIEncode(EmailAddress));
        if(subject != null && subject.Length > 0 )
        {
            asciiLink.Append("?subject=" + subject);
        }
        asciiLink.Append("\"");
        if (mouseoverTag != null && mouseoverTag.Length > 0)
        {
            asciiLink.Append(" title=\"" + mouseoverTag + "\"");
        }
        if (cssClass !=null && cssClass.Length > 0)
        {
            asciiLink.Append(" class=\"" + cssClass + "\"");
        }
        asciiLink.Append(">");
        asciiLink.Append(ASCIIEncode(VisibleAddress));
        asciiLink.Append("</a>");

        ltEmail.Text = asciiLink.ToString();      
    }

    protected string ASCIIEncode(string regularText)
    {
        regularText = regularText.Trim();

        StringBuilder encodeSB = new StringBuilder();
        char regularLetter;

        for (int j = 0; j < regularText.Length; j++)
        {
            // peel off 1 character at a time
            regularLetter = regularText[j];
            encodeSB.Append("&#" + Convert.ToInt32(regularLetter).ToString() + ";");
        }

        return encodeSB.ToString();
    }

Step 3 - Create a Test Page

Register the control at the top using whatever path and naming convention you've chosen.
<%@ Register Src="~/lab/maskemail/EmailMask.ascx" TagName="EmailMask" TagPrefix="dc" %>
Inside the ASP.NET page and control is used like below.
<dc:EmailMask ID="eMask" 
 CssClass="Summer" 
 EmailAddress="larryKing@cnn.com" 
 VisibleAddress="Email Larry King"   
 MouseoverTag="Send feedback" 
 Subject="Tonight's Show" 
 runat="server" />

Labels: , ,

 

Masking Your Email Address

Some of you are probably aware of spiders. They are these little programs that surf the internet looking for data. Some spiders assist search engines in helping you find the web page you are looking for. Those are the good spiders. There also exists evil spiders. They jump from web page to web page looking for email addresses. Once they find one, they send it to a database so someone can send you junk email. Not cool.

Hiding In Plain Sight

What we need is a way to display an email address so the reader of a web page can communicate with the web site, yet we also need to hide the address from the spider. The reader and the spider are looking at the same web page but at differently levels. The reader is looking at the browser's rendering of HTML. The spider is looking at raw HTML. Three ideas come to mind: ASCII codes, server-side mail forms and images. ASCII codes and images will look like email addresses on the screen, but nothing like an email address in the source code of the HTML document.

Method 1: ASCII

In HTML when you place "&#" in front of the ASCII code of a character the browser will write the character not the ASCII code to the screen. And because this article is being viewed by a browser, the code shots are images. The download will have the source in a text format.

The function below accepts an email address as a parameter and returns a masked email address that is made up of ASCII codes. When the browser writes the codes to the screen it will get converted back to text. Although it's possible for a spider to read and convert ASCII codes inside the HTML source, it's probably not that prevalent. The function goes character by character converting the email address. The last step is to merge the masked email address with the HTML mailto: tag. In order to minimize the chances a clever spider might look for the mailto:, this example maskes that word as well.
Function maskEmail(email) 
   For j= 1 to Len(email) 
      maskEmail = maskEmail & "&#" & asc(Mid(email,j,1)) & ";" 
   Next 
   maskEmail = "<a href=""m&#" & asc("a") & ";&#" & asc("i") & ";&#" &_ 
     asc("l") & ";&#" & asc("t") & ";o:" & maskEmail & """>" & maskEmail & "</a>" 
End Function
Then you can call that VBScript function from inside an ASP page.
<p>For more information email me at <%= maskEmail("someEmail@someDomain.net") %>.</p>

Method 2: Server-side Mail Forms

These are the contact forms you see everywhere these days. The user fills out a form, clicks submit, and hopes it gets to somebody. This is great for the recipient, because their email address never appears on the site. However, some users don't trust filling out a form and will withhold feedback. Recently I was trying to open a new account with eFax.com. Their order entry page was down so I filled out a form alerting them to the problem. After detailing the problem the form rejected because I didn't already have an account with them. They didn't have a direct email address listed anywhere else, so I became a customer of one of their competitors.

Method 3: Images

I believe the ASCII method will work for a little while. Eventually as that trick becomes more popular, the spiders will get smarter. Who knows maybe the developer that writes the code for those evil little email spiders is reading this article right now. If we created an image with text of our email, the spiders would be truly be defeated. However creating an image for every email address in PhotoShop would be a hassle. And then what happens when we change fonts when the site gets redesigned? Creating the email images by hand isn't an option. We need to automate.

For this version I extended the ImageToText code sample at yyyZ.net.

Method 4: Chopped Javascript

Now that you have an email image or icon, you may want to assist the users so they click on an email address image it behaves as if it were a hypertext link. This means having their email client launched with the TO line filled out for them. In order for this to happen with the email image, we need to hack out a chopped Javascript function. There are many possible ways to write it. In this example I wrote a function that accepts an email address into 3 parts. It then reassembles the email and launches the email client. How you chop up the email address is up to you. Also feel free to change the sequence of the parameters.
<script language="JavaScript" type="text/javascript">  
function postage(one,two,three){ 
   window.location = 'mailto:'+one+two+three;} 
</script> 
<img src="123.jpg" alt="email" width="100" 
    height="40" border="0" 
    onmouseover="this.style.cursor='hand'" 
    onclick="postage('larryking@c','n','n.com');"/> 

Lab Demos

Mask Email Image Generator (Email Obfuscator)

Mask Email ASCII Generator

PHP Version of Masking Email Addresses

Labels: , , , ,

 

ASP.NET Email Using VB

This article is for ASP.NET 1.x. For a 2.0 snippet read Sending Email in ASP.NET 2.0 (VB.NET).

By now we all know how to send server-side email using classic ASP. We either use Microsoft's CDONTS technology or a third-party component such as ServerObjects's ASPMail or Persist's ASPEmail. With ASP.NET server-side email is built-in and can be accessed using the System.Web.Mail namespace. In this article, I will demonstrate how to generate an email with form validation.

The Example

A lot of people post their resume on their web site. The advantage of having a resume available for recruiters and potential employers on a web site is valuable. The downside is you don't know who is reading your resume. A simple way to resolve that is to set up a form where the user requests that the resume be emailed to them. Then you can blind carbon copy yourself and you'll know exactly who showed interest. No more guessing if an employer pulled your resume, you'll have a receipt.

The Form

Elements we will want to capture are name, email, company, and the format of the resume they wish to receive. All fields will be required to successfully submit the form. Let's code the form using ASP.NET Web Form controls and attach validation controls.
<div id="requestResume" runat="server"> 
<!-- The values on this FORM will be posted back to the server. --> 
<!-- We will add the 'runat="server"' to the FORM and controls --> 
<form id="Form1" method="post" runat="server"> 
<table> 
<tr><td>Name</td>
<td><input type="text" id="txtName" 
value="" size="30" maxlength="50" 
runat="server" name="txtName"/> 
<!-- txtName is required. We will attach a 
RequiredFieldValidator by assigning 
txtName as the ControlToValidate --> 
<asp:RequiredFieldValidator id="valRequiredName" 
runat="server"     
ControlToValidate="txtName"     
ErrorMessage="* You must enter your Full Name."
     Display="dynamic".>
</td></tr> 
<tr><td>Email</td>
<td> <input type="text" id="txtEmail" 
value="" size="30" maxlength="50" 
runat="server" NAME="txtEmail"/> 
<!-- txtEmail is both required and must be a valid email address. -->
<asp:RequiredFieldValidator id="valRequiredEmail" 
runat="server"     
ControlToValidate="txtEmail"     
ErrorMessage="* You must enter your Email address."     
Display="dynamic"/>
<!-- txtEmail will be validated using Regular Expression. 
It is also attached to txtEmail via the ControlToValidate property. --> 
<asp:RegularExpressionValidator id="valValidEmail" 
runat="server"     
ControlToValidate="txtEmail"     
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"     
ErrorMessage="* You must enter a valid Email address"     
Display="dynamic"/> 
</td></tr> 
<tr><td>Company</td>
<td> <!-- txtCompany works exactly like txtName. --> 
<input type="text" id="txtCompany" value="" size="30" 
maxlength="50" runat="server" 
NAME="txtCompany"/> 
<asp:RequiredFieldValidator id="valRequiredCompany" 
runat="server"     
ControlToValidate="txtCompany"     
ErrorMessage="* You must enter your Company name."     
Display="dynamic"/>
</td></tr> 
<tr><td>Resume Format</td>
<td> 
<!-- The dropdown list of resume formats 
will be assigned on the server --> 
<asp:DropDownList id="selResume" Runat="server"/>
</td></tr> 
<tr>
<td></td>
<td> 
<!-- When the FORM is submitted it will 
execute the "btnSubmit_OnClick" 
Subroutine on the server. --> 
<asp:button type="submit" name="btnSubmit" 
onclick="btnSubmit_OnClick" 
text="Request Resume" 
runat="server"/> </td></tr> 
</table> 
</form> 
</div>

Server-Side Code (VB.NET)

Regardless of what language you utilize, the above FORM will be coded the same way. To proceed on the server-side code, we need to pick a language. C# and Visual Basic are the two most popular at this time. Let's proceed in VB. The first line imports the ASP.NET code needed to perform sending email.
<%@ Import Namespace="System.Web.Mail" %> 
<script language="VB" runat="server">     
Sub Page_Load()         
'=== When the page first loads populate the Resume Format dropdown         
If NOT IsPostBack() Then            
   Call populateResumeFormats()            
   selResume.DataValueField = "Value"            
   selResume.DataTextField = "Key"            
   selResume.DataBind()         
End If     
End Sub     

Public Sub populateResumeFormats         
'=== create a HashTable to populate the dropdown.         
   Dim dropResume As New HashTable(4)         
   dropResume.Add("Word 97 (.RTF)", "resume.rtf")         
   dropResume.Add("HTML", "resume.htm")         
   dropResume.Add("Word 2002", "resume.doc")         
   dropResume.Add("Text", "resume.txt")         
   selResume.DataSource = dropResume     
End Sub     

Sub btnSubmit_OnClick(o as Object, e as EventArgs)         
'=== The Page.IsValid call checks all the validation controls. 
'=== If they all pass then the form is valid.         
If Page.IsValid Then             
'=== no longer display the FORM, display a status message. 
   requestResume.InnerHTML = "You will receive an email shortly with my resume.
 Thank you for your interest."             
   Call sendResume         
End If     
End Sub     

Sub sendResume        
'=== create a MailMessage         
  Dim resumeEmail as New MailMessage         
  Dim strResumeFilePath as String         
'=== To, CC, BCC, From, Subject are self-explainatory         
  resumeEmail.To = txtEmail.value
  resumeEmail.BCC = "larryking@cnn.com"         
  resumeEmail.From = "larryking@cnn.com"         
  resumeEmail.Subject = "Resume for Larry King"         
  resumeEmail.BodyFormat = MailFormat.text         
  resumeEmail.Body = txtName.value & ", attached is a copy of my resume. 
I look forward to working with you. - MAS "         
'=== for this example all versions of the resume reside in the 
/resume directory           
  strResumeFilePath = Server.MapPath("/") & "\resume\" & selResume.SelectedItem.value         
'=== create an attachment and add the file path to that attachment         
  Dim resumeAttachment as New MailAttachment(strResumeFilePath)            
  resumeEmail.Attachments.Add(resumeAttachment)         
'=== send the email         
  SmtpMail.Send(resumeEmail)     
End Sub </script>

Last Words

Pretty straightforward isn't it? Now you have a working resume mailer. The employer can specify the preferred format, and the potential employee gets to track who is viewing the resume.

This article was written in 2001 for ASP.NET 1.0. Forgive the non XHTML.

Labels: , ,

 

Digital Colony Copyright © 1999-2009 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.