Sending Email in ASP.NET 2.0 with attachments


Sending Email in ASP.NET 2.0

(Taken from: http://aspnet.4guysfromrolla.com/articles/072606-1.aspx)

Introduction
Email serves as a ubiquitous, asynchronous notification and information distribution system. Not surprisingly, there are many web development scenarios where server-side code needs to generate an email and scuttle it off to the intended recipient. The email may be destined for a user of the website, informing them of their newly created user account, reminding them of their forgotten password, or emailing them an invoice. Or it may be destined for a web developer or site administrator, providing information of an unhandled exception that just transpired or user feedback.

Fortunately, ASP.NET makes sending email a breeze. The .NET Framework version 1.x included a number of classes in the System.Web.Mail class that allowed programmatically sending an email with a few scant lines of code. While this namespace and these classes still exist in the .NET Framework version 2.0, they have been deprecated in favor of new mail-related classes found in the System.Net.Mail namespace. (For an article on sending email in ASP.NET version 1.x, see Sending Email from an ASP.NET 1.x Web Page or consult www.SystemWebMail.com.)

In this article we’ll look at the classes in the System.Net.Mail namespace and see how to send an email from an ASP.NET 2.0 page’s code-behind class. We’ll also look at specifying relay server information in Web.config and how this information can be used in some of the built-in ASP.NET server controls for sending emails (such as when a user creates an account or needs a password reminder/reset). Read on to learn more!

Exploring the Classes in the System.Net.Mail Namespace
There are 16 different classes in the System.Net.Mail namespace, all related to send email to a specified Simple Mail Transfer Protocol (SMTP) server for delivery. The two core classes in this namespace are:

  • MailMessage – represents an email message; has properties like From, To, Subject, Body, and so on.
  • SmtpClient – sends a specified MailMessage instance to a specified SMTP server.

When sending an email from an ASP.NET 2.0 page you will, typically:

  1. Create a MailMessage object
  2. Assign its properties
  3. Create an instance of the SmtpClient class
  4. Specify details about the SMTP server to use (if they’re not already specified within Web.config)
  5. Send the MailMessage via the SmtpClient object’s Send method

Steps 1 and 2 may be bypassed as the SmtpClient class’s Send method can accept either a MailMessage object or four strings, representing the from, to, subject, and body contents of the email message.

The System.Net.Mail namespace’s other classes allow for more advanced email functionality. There are classes that can be used to add attachments to an email message, to embed objects within an email, to specify SMTP server authentication information, and Exception-derived classes for handling SMTP-specific exceptions. We’ll examine using some of these other classes for more advanced scenarios in future articles.

Providing the SMTP Server’s Details
When sending an email to a friend from Outlook or GMail, the email program establishes a connection with a relay server and sends the contents of the email message, along with information such as the date the email was composed, the email body’s format (text or HTML, for example), the recipient(s), and so on. The relay server accepts the message and then connects to the recipient’s SMTP server and sends the message. Once the message has been delivered, the recipient can, at some later point in time, pull down the message using a different protocol (such as IMAP or POP3).

Therefore, to send an email from an ASP.NET page we need to provide the SmtpClient class with information about the relay server. Along with the hostname of the relay server, you can specify the port (typically port 25 is used), whether or not to use SSL when communicating your email message contents to the relay server, and authentication credentials (if necessary). Alternatively, if you have a local SMTP service installed on your web server, it may periodically monitor a particular “drop-off” directory, sending any messages that appear in that directory. You can configure whether the SmtpClient class relays its email messages to a separate relay server or if it drops it off in a specified pickup directory through the DeliveryMethod property.

The relay server information used by the SmtpClient class can be specified programmatically, through the SmtpClient class’s properties, or can be centralized in Web.config. To use the Web.config approach, add a <system.net> element within the <configuration> element. Then, add a <mailSettings> element that contains an <smtp> element whose settings are specified within its <network> child element, like so:

<configuration>
  <!-- Add the email settings to the <system.net> element -->
  <system.net>
    <mailSettings>
      <smtp>
        <network 
             host="relayServerHostname" 
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>
 
  <system.web>
    ...
  </system.web>
</configuration>

The host attribute contains the relayServerHostname. If you are using an external relay server, the relayServerHostname might be something like smtp.yourisp.com. If the relay server’s port number is something other than the typical port 25, specify it through the port attribute. Most external relay servers require authentication of some sort (in order to prevent anonymous spammers from sending their garbage through the relay). The userName and password attributes can be provided in the case where username/password authentication is needed.

Only a subset of the SmtpClient properties can be specified through settings in Web.config. To customize the other SmtpClient properties – EnableSsl, Timeout, and so on – set them programmatically when sending the email (step 4 from the list of five steps examined earlier in this article).

Sending an Administrator Email Through a Feedback Web Page
To illustrate sending an email using the MailMessage and SmtpClient classes, I’ve created a simple feedback page example. In this page the user is prompted for their email address, the subject of their feedback, and their feedback.

<table border="0">
<tr>
<td><b>Your Email:</b></td>
<td><asp:TextBox runat="server" ID="UsersEmail" Columns="30"></asp:TextBox></td>
</tr>
<tr>
<td><b>Subject:</b></td>
<td><asp:TextBox runat="server" ID="Subject" Columns="30"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2">
<b>Body:</b><br />
<asp:TextBox runat="server" ID="Body" TextMode="MultiLine" Columns="55" Rows="10"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button runat="server" ID="SendEmail" Text="Send Feedback" />
</td>
</tr>
</table>

The feedback form.

Once the user has supplied the feedback information and clicked the “Send Feedback” button, a postback ensues and the Button’s Click event fires. Inside the event handler, a MailMessage object is created and its To, From, Subject, and Body properties are set according to the information provided by the user. With the MailMessage object created and its properties populated, the email is then sent through the SmtpClient class’s Send method.

Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
'!!! UPDATE THIS VALUE TO YOUR EMAIL ADDRESS
Const ToAddress As String = "you@youremail.com"

'(1) Create the MailMessage instance
Dim mm As New MailMessage(UsersEmail.Text, ToAddress)

'(2) Assign the MailMessage's properties
mm.Subject = Subject.Text
mm.Body = Body.Text
mm.IsBodyHtml = False

'(3) Create the SmtpClient object
Dim smtp As New SmtpClient

'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)
End Sub

We didn’t need to set any of the SmtpClient class’s properties here in code because they have been specified in Web.config (download the complete code at the end of this article to run this application on your computer).

The received email.

Conclusion
Along with a plethora of other improvements from ASP.NET 1.x, the email sending capabilities in ASP.NET 2.0 have been updated and moved to a new namespace, System.Net.Mail. In 2.0 the relay server settings can easily be decoupled from the ASP.NET code and moved into the Web.config file, as we saw in this example. Moreover, there’s better support for relay server authentication. Future articles will explore more advanced email scenarios, such as: crafting HTML-formatted emails, sending attachments, embedding objects within the email body, handling SMTP/relay server-related exceptions, and so on.

Download Demo

Sending Email in ASP.NET 2.0: HTML-Formatted Emails, Attachments, and Gracefully Handling SMTP Exceptions

(Taken from: http://aspnet.4guysfromrolla.com/articles/080206-1.aspx)

Introduction
The .NET Framework version 2.0 includes a new namespace (System.Net.Mail) and new classes for sending email. (The namespace (System.Web.Mail) and classes used in the .NET Framework version 1.x still exist for backwards compatibility.) Last week we examined how to use the MailMessage and SmtpClient classes in the System.Net.Mail namespace for sending simple, plain-text email messages.

This article looks at the more advanced email-related options. We’ll see how to send HTML-formatted emails, how to include attachments, and how to gracefully handle SMTP exceptions when sending an email (such as invalid relay server credentials or if the relay server is offline). Read on to learn more!

Sending HTML-Formatted Emails
In Sending Email in ASP.NET 2.0 we saw how to send plain-text emails by assigning the contents of the email to the MailMessage class’s Body property. To send HTML-formatted emails, simply set the Body property to the HTML content to send, and then mark the MailMessage class’s IsBodyHtml property to True.

To demonstrate sending an HTML-formatted message, I created a sample named HtmlEmail.aspx available for download at the end of this article. The germane code follows:

'(1) Create the MailMessage instance
Dim mm As New MailMessage(FromEmailAddress, ToEmailAddress)

'(2) Assign the MailMessage's properties
mm.Subject = "HTML-Formatted Email Demo Using the IsBodyHtml Property"
mm.Body = "<h2>This is an HTML-Formatted Email Send Using the <code>IsBodyHtml</code> Property</h2><p>Isn't HTML <em>neat</em>?</p><p>You can make all sorts of <span style=""color:red;font-weight:bold;"">pretty colors!!</span>.</p>"
mm.IsBodyHtml = True

'(3) Create the SmtpClient object
Dim smtp As New SmtpClient

'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)

As you can see, simply set the Body property to the HTML content to send and the IsBodyHtml property to True, and you’re done! The actual email content that gets sent to the relay server (and eventually down to the recipient’s email client), looks something like the following:

x-sender: ToEmailAddress
x-receiver: FromEmailAddress
mime-version: 1.0
from: FromEmailAddress
to: ToEmailAddress
date: 25 Jul 2006 15:06:44 -0700
subject: HTML-Formatted Email Demo Using the IsBodyHtml Property
content-type: text/html; charset=us-ascii
content-transfer-encoding: quoted-printable

<h2>This is an HTML-Formatted Email Send Using the <code>IsBodyHtml</code>=
Property</h2><p>Isn't HTML <em>neat</em>?</p><p>You can make all sorts=
of <span style=3D"color:red;font-weight:bold;">pretty colors!!</span>.</p>

Viewing the Email Content Sent to the Relay Server

Interested in viewing the actual content sent to the relay server by the SmtpClient class (like the content shown above)? In Sending Email in ASP.NET 2.0 we discussed how the SmtpClient class can be configured to send the email to a relay server or have it dropped off in a specified directory. Using the latter option, we can explore the actual email content that would otherwise have been sent to the relay server. Check out the Web.config file in the code available for download at the end of this article – there’s a commented out <smtp> element that shows how to configure the SmtpClient class to dump the email’s contents to a specified directory.

The email client – assuming it supports HTML-formatted emails – will display the HTML content within the email.

The HTML-formatted email.

Caveats on Sending HTML-Formatted Emails

When sending HTML-formatted emails, understand that the HTML you see on your screen may differ quite a bit from what your recipients see. Most all email clients strip out potentially dangerous HTML content (ActiveX controls and the like), many prevent JavaScript from running, and most handle external styles poorly. For a more thorough discussion on potential problems with sending HTML-formatted emails, check out Top 10 HTML Email Mistakes and CSS and Email, Kissing in a Tree.


Including Attachments

The MailMessage class has an Attachments property that is a collection of Attachment class instances. You can attach an existing file on the web server to the email message or base the content’s attachment on a Stream. To illustrate sending emails will attachments, I created a demo where the visitor can fill out a feedback-like form to have an email sent to administrator. However, this feedback form allows the visitor to pick a file from their computer to be attached to the email sent from the web page (much like how the web-based email web applications – Hotmail, GMail, etc. – allow you to attach a file from your computer when sending an email).

To allow the visitor to attach a file from their computer, we need to allow the user to upload a file from their machine to the web server. This can be easily accomplished using the FileUpload control (which is new to ASP.NET 2.0). Let’s look at the declarative syntax used for creating the user interface for this demo:

<table border="0">
<tr>
<td><b>Your Email:</b></td>
<td><asp:TextBox runat="server" ID="UsersEmail" Columns="30"></asp:TextBox></td>
</tr>
<tr>
<td><b>File to Send:</b></td>
<td>
<asp:FileUpload ID="AttachmentFile" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<b>Body:</b><br />
<asp:TextBox runat="server" ID="Body" TextMode="MultiLine" Columns="55" Rows="10"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button runat="server" ID="SendEmail" Text="Send Feedback" />
</td>
</tr>
</table>

The FileUpload control renders as a <input type="file" ... /> HTML element, which, in the browser, is displayed as a textbox with a Browse button. When clicked, a dialog box is opened from which the user can pick a file from their computer.

The user is prompted for a file to upload.

After filling in the feedback form, selecting a file to upload, and clicking the “Send Feedback” button, a postback occurs, sending the contents of the selected file up to the web server. In the “Send Feedback” Button’s Click event handler, a MailMessage object is created and an attachment is added. Since the FileUpload provides a Stream to the uploaded data, we can simply point the new Attachment object at this Stream. There’s no need to save the uploaded file to the web server’s file system.

'Make sure a file has been uploaded
If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
Throw New ApplicationException("Egad, a file wasn't uploaded... you should probably use more graceful error handling than this, though...")
End If

'(1) Create the MailMessage instance
Dim mm As New MailMessage(FromEmailAddress, ToEmailAddress)

'(2) Assign the MailMessage's properties
mm.Subject = "Emailing an Uploaded File as an Attachment Demo"
mm.Body = Body.Text
mm.IsBodyHtml = False

'Attach the file
mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))

'(3) Create the SmtpClient object
Dim smtp As New SmtpClient

'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)

The Attachment constructor overload used in the code sample above expects two inputs: a reference to the Stream that contains the data to attach, and the name to use for the attachment. The FileUpload’s InputStream and FileName properties are used for these two values.

The email, which includes the attachment.

Handling SMTP Exceptions
When sending an email from an ASP.NET page, what happens if the relay server is down, or if the authentication information used is invalid? In the face of an SMTP error, the SmtpClient class will throw an SmtpException exception. To gracefully handle such problems, we can add exception handling code around the code that sends the email. If there’s an SmtpException we can then display a more friendly and informative error message (or, perhaps, write the email’s contents to a file to be sent later).

In the download at the end of this article I’ve included a demo that allows the visitor to specify the relay server to use, along with authentication information. If there’s an error in attempting to send an email, a client-side alert box is displayed, explaining the problem. To test this out, enter an invalid relay server hostname or invalid credentials for a relay server that requires authentication.

Try
'(1) Create the MailMessage instance
Dim mm As New MailMessage(FromEmailAddress, ToEmailAddress)

'(2) Assign the MailMessage's properties
mm.Subject = "Test Email... DO NOT PANIC!!!1!!!111!!"
mm.Body = "This is a test message..."
mm.IsBodyHtml = False

'(3) Create the SmtpClient object
Dim smtp As New SmtpClient

'Set the SMTP settings...
smtp.Host = Hostname.Text
If Not String.IsNullOrEmpty(Port.Text) Then
smtp.Port = Convert.ToInt32(Port.Text)
End If

If Not String.IsNullOrEmpty(Username.Text) Then
smtp.Credentials = New NetworkCredential(Username.Text, Password.Text)
End If

'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)

'Display a client-side popup, explaining that the email has been sent
ClientScript.RegisterStartupScript(Me.GetType(), "HiMom!", String.Format("alert('An test email has successfully been sent to {0}');", ToAddress.Replace("'", "\'")), True)

Catch smtpEx As SmtpException
'A problem occurred when sending the email message
ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\'")), True)

Catch generalEx As Exception
'Some other problem occurred
ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\'")), True)
End Try

This code catches both SMTP-specific error messages and general ones (such as assigning invalid email addresses to the MailMessage object’s To or From properties). In either case, a client-side alert box is displayed informing the user of the details of the error.

An error message is displayed in a client-side alert box.

Conclusion
In this article we saw how to send HTML-formatted emails, send emails with attachments, and gracefully handle exceptions arising from sending an email message. Sending an HTML-formatted email is as simple as specifying the HTML content in the Body property and setting the IsBodyHtml property to True. The real challenge comes in making sure the HTML content used is rendered as expected by the popular email clients. To add an attachment to an email, simply add an Attachment object to the MailMessage‘s Attachments collection. The data for the attachment can come from a file on the web server or from a Stream. Finally, to handle SMTP-level exceptions, add exception handling code that catches the SmtpException thrown by the SmtpClient class when unable to transport the message to the relay server.

Download Code

Advertisements

Sending Emails with ASP and PHP


Hi,
I think many of new web developers come around a situation where they have to send emails (like registration emails of password-user name emails or newsletters) from their developed sites.
And I had also come around such situations where I had to send mails from PHP or ASP scripts. I found some useful resources and I have tested some of they successfully and also made some modifications to use them correctly. I will give some of them here. Hope it will help us to know the scripting power better.

Sending mails with ASP (CDOSYS):

CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of messaging applications.

CDOSYS is a built-in component in ASP. We will show you how to use this component to send e-mail with ASP.

Sending a text e-mail:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.TextBody=”This is a message.”
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with Bcc and CC fields:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.Bcc=”someoneelse@somedomain.com
myMail.Cc=”someoneelse2@somedomain.com
myMail.TextBody=”This is a message.”
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.HTMLBody = “<h1>This is a message.</h1>”
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a website:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.CreateMHTMLBody “http://www.w3schools.com/asp/
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a file on your computer:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.CreateMHTMLBody “file://c:/mydocuments/test.htm
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with an Attachment:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.TextBody=”This is a message.”
myMail.AddAttachment “c:\mydocuments\test.txt”
myMail.Send
set myMail=nothing
%>

Sending a text e-mail using a remote server:

<%
Set myMail=CreateObject(“CDO.Message”)
myMail.Subject=”Sending email with CDO”
myMail.From=”mymail@mydomain.com
myMail.To=”someone@somedomain.com
myMail.TextBody=”This is a message.”
myMail.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusing&#8221;)=2
‘Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserver“) _
=”smtp.server.com”
‘Server port
myMail.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserverport“) _
=25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
%>

Sending mails with SMTP Authentication:

<%

Const cdoSendUsingPickup = 1 ‘Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 ‘Send the message using the network (SMTP over the network).

Const cdoAnonymous = 0 ‘Do not authenticate
Const cdoBasic = 1 ‘basic (clear-text) authentication
Const cdoNTLM = 2 ‘NTLM

Set objMessage = Server.CreateObject(“CDO.Message”)
objMessage.Subject = “Example CDO Message”
objMessage.Sender = “me@mydomain.com
objMessage.From = “me@mydomain.com
objMessage.To = “recipient@test.com
objMessage.TextBody = “This is some sample message text..” & vbCRLF & “It was sent using SMTP authentication.”

‘==This section provides the configuration information for the remote SMTP server.

objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusing“) = 2

‘Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserver“) = “mail.your.com

‘Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpauthenticate“) = cdoBasic

‘Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusername“) = “youruserid

‘Your password on the SMTP server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendpassword“) = “yourpassword

‘Server port (typically 25)
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserverport“) = 25

‘Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpusessl“) = False

‘Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout“) = 60

objMessage.Configuration.Fields.Update
objMessage.Send

%> 

Note :
Change the SMTP Server with your mail.yourdomain.com
Username –> Change with your email account in this format (email@domain.com).
Password-> Your email password.

Sending Emails with CDONTS:

Using CDONTS to send a text based email message.

<%
    Dim MyBody
    Dim MyCDONTSMail

    Set MyCDONTSMail = CreateObject(“CDONTS.NewMail”)
    MyCDONTSMail.From= “somebody@nowhere.com
    MyCDONTSMail.To= “nobody@nowhere.com
    MyCDONTSMail.Subject=”This is a Test”
    MyBody = “Thank you for ordering that stuff” & vbCrLf
    MyBody = MyBody & “We appreciate your business” & vbCrLf
    MyBody = MyBody & “Your stuff will arrive within 7 business days”
    MyCDONTSMail.Body= MyBody
    MyCDONTSMail.Send
    set MyCDONTSMail=nothing
%>

Using CDONTS to send a HTML based email message.

You’ll get the general idea..notice how you have to add extra double quotes inside the HTML. You can use any valid HTML. Just make sure you link the images back to your webserver so that the recipient doesn’t get a broken image. If the recipient’s email program doesn’t support HTML this is not always a good way to send email, but most do in my experience and if they don’t they will still get the message… it will just look kinda strange.

<%
    Dim MyCDONTSMail2
    Dim HTML
    Set MyCDONTSMail2 = CreateObject(“CDONTS.NewMail”)
    HTML = “<!DOCTYPE HTML PUBLIC””-//IETF//DTD HTML//EN””>”
    HTML = HTML & “<html>”
    HTML = HTML & “<head>”
    HTML = HTML & “<title>Sending CDONTS Email Using HTML</title>”
    HTML = HTML & “</head>”
    HTML = HTML & “<body bgcolor=””FFFFFF””>”
    HTML = HTML & “<p><font size =””3″” face=””Arial””><strong>”
    HTML = HTML & “Name Of Store</strong><br>”
    HTML = HTML & “Incoming Customer Order</strong></p>”
    HTML = HTML & “<p align = “”center””>Bla Bla Bla Bla Bla</p>”
    HTML = HTML & “</body>”
    HTML = HTML & “</html>”
    MyCDONTSMail2.From= “somebody@somewhere.com
    MyCDONTSMail2.To=”nobody@somewhere.com
    MyCDONTSMail2.Subject=”Incoming Customer Order”
    MyCDONTSMail2.BodyFormat=0
    MyCDONTSMail2.MailFormat=0
    MyCDONTSMail2.Body=HTML
    MyCDONTSMail2.Send
    set MyCDONTSMail2=nothing
%>

Using CDONTS to send a file attachment and have a Carbon Copy Recipient.

<%
    Dim MyBody2
    Dim MyCDONTSMail3

    Set MyCDONTSMail3 = CreateObject(“CDONTS.NewMail”)
    MyCDONTSMail3.From= “somebody@nowhere.com
    MyCDONTSMail3.To= “nobody@nowhere.com
    MyCDONTSMail3.Cc=”nobody2@nowhere.com
    MyCDONTSMail3.Subject=”This is a Test”
   
    MyCDONTSMail3.AttachFile Server.MapPath(“/somedirectory/bla.txt”)
    ‘ or you could specify the path exactly if you knew it like below
    ‘MyCDONTSMail3.AttachFile (“C:\inetpub\wwwroot\somedirectory\bla.txt”)
    
    MyBody2 = “Thank you for ordering that stuff” & vbCrLf
    MyBody2 = MyBody2 & “We appreciate your business” & vbCrLf
    MyBody2 = MyBody2 & “Your stuff will arrive within 7 business days”
    MyCDONTSMail3.Body= MyBody2
    MyCDONTSMail3.Send
    set MyCDONTSMail3=nothing
%>

When sending an attachment this is just a very simple example. There are certain encoding options and file type settings that you may also want to set.
 

Sending Email With PHP:

The PHP mail() Function
The PHP mail() function is used to send emails from inside a script.

Syntax: mail(to,subject,message,headers,parameters)

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email.
Note: This parameter cannot contain any newline characters

message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters

headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)

parameters Optional. Specifies an additional parameter to the sendmail program

Note: For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.
——————————————————————————–

PHP Simple E-Mail
The simplest way to send an email with PHP is to send a text email.

In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail:

<?php
$to = “someone@example.com“;
$subject = “Test mail”;
$message = “Hello! This is a simple email message.”;
$from = “someonelse@example.com“;
$headers = “From: $from”;
mail($to,$subject,$message,$headers);
echo “Mail Sent.”;
?>
——————————————————————————–

PHP Mail Form:
With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail address:

<html>
<body><?php
if (isset($_REQUEST[’email’]))
//if “email” is filled out, send email
  {
  //send email
  $email = $_REQUEST[’email’] ;
  $subject = $_REQUEST[‘subject’] ;
  $message = $_REQUEST[‘message’] ;
  mail( “someone@example.com“, “Subject: $subject”,
  $message, “From: $email” );
  echo “Thank you for using our mail form”;
  }
else
//if “email” is not filled out, display the form
  {
  echo “<form method=’post’ action=’mailform.php’>
  Email: <input name=’email’ type=’text’ /><br />
  Subject: <input name=’subject’ type=’text’ /><br />
  Message:<br />
  <textarea name=’message’ rows=’15’ cols=’40’>
  </textarea><br />
  <input type=’submit’ />
  </form>”;
  }
?></body>
</html>

  • This is how the example above works:
    First, check if the email input field is filled out
    If it is not set (like when the page is first visited); output the HTML form
    If it is set (after the form is filled out); send the email from the form
    When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email

Sending mails with Attachment : (with attachment size limit checking)

<?php
   include “../../common/error.php”;
   if ($_SERVER[‘REQUEST_METHOD’]==”POST”){
   $to=$_POST[‘to’];
   $subject=$_POST[‘subject’];
   $from = stripslashes($_POST[‘fromname’]).”<“.stripslashes($_POST[‘fromemail’]).”>”;
  

   // generate a random string to be used as the boundary marker
   $mime_boundary=”==Multipart_Boundary_x”.md5(mt_rand()).”x”;

   // store the file information to variables for easier access
   $tmp_name = $_FILES[‘filename’][‘tmp_name’];
   $type = $_FILES[‘filename’][‘type’];
   $name = $_FILES[‘filename’][‘name’];
   $size = $_FILES[‘filename’][‘size’];
/**********************************************************/
echo “Size=”.$size;
if($size>122880)
  {
  echo “Attachment Size Exceeds 1MB Limit”;
  echo “<br><a href=send_mail.php>try Again</a>”;
   exit();
  }
/**********************************************************/
   // here we’ll hard code a text message
   // again, in reality, you’ll normally get this from the form submission
   $message = “Note File Attached: $name \n”.$_POST[‘message’];
/***************************************************/
   if($_FILES[‘filename’][‘tmp_name’]==””)
   {
    echo “No files attached”;
    $message =$_POST[‘message’];
 $headers.=”MIME-Version: 1.0\r\n”;
 $headers.=”Content-type: text/html;”.”charset=iso-8859-1\r\n”;
 $headers.=”From:”.$from.”\r\n”;

 if (mail($to, $subject, $message, $headers))
         {
  
   }
      else
    {
         echo “Failed to send”;
         echo “<br><a href=send_mail.php>try Again</a>”;
    } 
 
 
   } 
/**************************************************/  

   // if the upload succeded, the file will exist
   if (file_exists($tmp_name)){

      // check to make sure that it is an uploaded file and not a system file
      if(is_uploaded_file($tmp_name)){

         // open the file for a binary read
         $file = fopen($tmp_name,’rb’);

         // read the file content into a variable
         $data = fread($file,filesize($tmp_name));

         // close the file
         fclose($file);

         // now we encode it and split it into acceptable length lines
         $data = chunk_split(base64_encode($data));
     }

      // now we’ll build the message headers
      $headers = “From: $from\r\n” .
         “MIME-Version: 1.0\r\n” .
         “Content-Type: multipart/mixed;\r\n” .
         ” boundary=\”{$mime_boundary}\””;

      // next, we’ll build the message body
      // note that we insert two dashes in front of the
      // MIME boundary when we use it
      $message = “This is a multi-part message in MIME format.\n\n” .
         “–{$mime_boundary}\n” .
         “Content-Type: text/plain; charset=\”iso-8859-1\”\n” .
         “Content-Transfer-Encoding: 7bit\n\n” .
         $message . “\n\n”;

      // now we’ll insert a boundary to indicate we’re starting the attachment
      // we have to specify the content type, file name, and disposition as
      // an attachment, then add the file content and set another boundary to
      // indicate that the end of the file has been reached
      $message .= “–{$mime_boundary}\n” .
         “Content-Type: {$type};\n” .
         ” name=\”{$name}\”\n” .
         //”Content-Disposition: attachment;\n” .
         //” filename=\”{$fileatt_name}\”\n” .
         “Content-Transfer-Encoding: base64\n\n” .
         $data . “\n\n” .
         “–{$mime_boundary}–\n”;

      // now we just send the message
      if (@mail($to, $subject, $message, $headers))
         {
     
   }
      else
    {
         echo “Failed to send”;
         echo “<br><a href=send_mail.php>try Again</a>”;
      } 
   }
} else {
?>
<html>
<head>
<title>Send E-mail with Attchment</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
<style type=”text/css”>
<!–
body {
 margin-left: 0px;
 margin-top: 0px;
 margin-right: 0px;
 margin-bottom: 0px;
}
–>
</style>
<script language=”javascript” type=”text/javascript”>

function CheckFields()
 {
  //——-E-Mail Check———–
   if(!document.form1.to.value.length)
    {
    alert(“To E-Mail Address can’t be left blank”);
    document.form1.to.focus();
    return false;
 }
  if (document.form1.to.value.indexOf(‘@’) == -1) {
    alert(“Error in To E-mail address”);
    document.form1.to.focus();
    return false;
 }
 if (document.form1.to.value.indexOf(‘.’) == -1) {
    alert(“Error in To E-mail address”);
    document.form1.to.focus();
    return false;
 }

  if(!document.form1.fromname.value.length)
    {
    alert(“Your Name can’t be left blank”);
    document.form1.fromname.focus();
    return false;
 }

  if(!document.form1.fromemail.value.length)
    {
    alert(“Your E-Mail Address can’t be left blank”);
    document.form1.fromemail.focus();
    return false;
 }
if (document.form1.fromemail.value.indexOf(‘@’) == -1) {
    alert(“Error in From E-mail address”);
    document.form1.fromemail.focus();
    return false;
 }
 if (document.form1.fromemail.value.indexOf(‘.’) == -1) {
    alert(“Error in From E-mail address”);
    document.form1.fromemail.focus();
    return false;
 }
if(!document.form1.subject.value.length)
    {
    alert(“Subject can’t be left blank”);
    document.form1.subject.focus();
    return false;
 }
if(!document.form1.message.value.length)
    {
    alert(“Message can’t be left blank”);
    document.form1.message.focus();
    return false;
 }
 }

<script>
</head>
<body>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”
   enctype=”multipart/form-data” name=”form1″ onSubmit=”return CheckFields()”>
<table width=”100%” border=”0″>
  <tr bgcolor=”#0099FF”>
    <td height=”33″ colspan=”4″ align=”center” bgcolor=”#A6DBFF” >Send an e-mail</td>
  </tr>
  <tr>
    <td width=”20%” height=”21″ >To      </td>
    <td colspan=”3″><span >:</span>
        <input name=”to” type=”text” id=”to” size=”50″>
                <span >(Insert Multiple E-Mail Addresses with commas i.e. moon@sun.com,apolo@greece.com)</span></td>
  </tr>
  <tr bgcolor=”#0099FF”>
    <td height=”33″ bgcolor=”#D7EFFF”>
   <p >From name </p>   </td>
    <td width=”31%” bgcolor=”#D7EFFF”><span >:</span>
      <input name=”fromname” type=”text”>
      <span >(Your Name) </span></td>
    <td width=”12%” bgcolor=”#D7EFFF”><span >From e-mail </span></td>
    <td width=”37%” bgcolor=”#D7EFFF”><span >:</span>
      <input name=”fromemail” type=”text”>
      <span >(Your E-Mail Address)</span> </td>
  </tr>
  <tr>
    <td height=”33″ >Subject</td>
    <td colspan=”3″><span >:
      <input name=”subject” type=”text” id=”subject”>
    </span></td>
  </tr>
  <tr>
    <td height=”42″ valign=”top” bgcolor=”#EAF7FF” >Message      </td>
    <td colspan=”3″ valign=”middle” bgcolor=”#EAF7FF”><span >:</span>
      <textarea name=”message” cols=”80″ rows=”8″ id=”message”></textarea></td>
  </tr>
  <tr>
    <td height=”38″ >Attach File </td>
    <td colspan=”3″><span >:</span>
      <input name=”filename” type=”file”>
      <span >(Do Not Attach More Than 1MB)</span></td>
  </tr>
  <tr>
    <td height=”55″ colspan=”4″ align=”center” bgcolor=”#A6DBFF”><table width=”100%” border=”0″>
      <tr>
        <td width=”37%” valign=”bottom” >Powered by <a href=”http://www.ubk.co.in&#8221; mce_href=”http://www.ubk.co.in”>UBK</a&gt; </td>
        <td width=”22%”><input name=”Submit” type=”submit” value=”Send Mail”></td>
        <td width=”41%”> </td>
      </tr>
    </table>
    </td>
  </tr>
</table>
</form>
</body>
</html>
<?php } ?>