Trying to get a very simple classic asp form up and running on 123-reg.
123-reg provide a script to get this done but I have no idea how this script connects to the form I've made.
Here's my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form" target="_blank" action="script.asp" method="post">
Name: <input name="Name" type="text" /><br />
Customer ID: <input name="Customer ID" type="text" /><br />
Email Address: <input name="Email" type="text" /><br />
Comments:<br />
<textarea name="Comments" rows=5 cols=50></textarea>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
And this is the simple script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Secure Mail (ASP)</title>
</head>
<body>
<div id="container" class="index" style="padding:10px">
<br />
<br />
<h2>Secure Mail (ASP)</h2>
<br />
<%
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'To get the script for work please set the following values:
'Set the credentials for your email account to send the email from
username="MYUSERNAME" 'Insert your email account username between the double quotes
password="MYPASSWORD" 'Insert your email account password between the double quotes
'Set the from and to email addresses
sendFrom = "admin#MYURL.co.uk" 'Insert the email address you wish to send from
sendTo = "MYEMAIL" 'Insert the email address to send to in here
'DO NOT CHANGE ANY SCRIPT CODE BELOW THIS LINE.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This script demonstrates how to send an email using asmtp
'Create a CDO.Configuration object
Set objCdoCfg = Server.CreateObject("CDO.Configuration")
'Configure the settings needed to send an email
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="intmail.atlas.pipex.net"
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 0
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = username
objCdoCfg.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = password
objCdoCfg.Fields.Update
'Create the email that we are going to send
Set objCdoMessage = Server.CreateObject("CDO.Message")
Set objCdoMessage.Configuration = objCdoCfg
objCdoMessage.From = sendFrom
objCdoMessage.To = sendTo
objCdoMessage.Subject = "This is a test email."
'Add the email body text
objCdoMessage.TextBody = "Email sent using ASMTP from a ASP script."
On Error Resume Next
'Send the email
objCdoMessage.Send
'Check if an exception was thrown
If Err.Number <> 0 Then
'Response.Write "<FONT color=""Red"">Error: " & Err.Description & " (" & Err.Number & ")</FONT><br/>"
Else
Response.Write "<FONT color=""Green"">The email has been sent to " & sendTo & ".</FONT>"
End If
'Dispose of the objects after we have used them
Set objCdoMessage = Nothing
Set objCdoCfg = Nothing
Set FSO = nothing
Set TextStream = Nothing
%>
</div>
</body>
</html>
I know the script works as it sends the email, however none of the information included in the HTML form seems to be included.
Don't usually work with forms so any advice would be gratefully received.
Thanks,
Dan
Nowhere in the asp are you requesting the form data to include in your email.
For example, instead of this in your asp:
sendTo = "MYEMAIL" 'Insert the email address to send to in here
You should use the email from the form:
sendTo = Request.Form("Email") 'Insert the email address to send to in here
You may want to validate the email address first:
if isEmailValid(Request.Form("Email")) = true then
'#### Send your email
else
'#### Email was invalid, give the user an error
response.write "Invalid email address"
end if
Function isEmailValid(email)
Set regEx = New RegExp
regEx.Pattern = "^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w{2,}$"
isEmailValid = regEx.Test(trim(email))
End Function
To confirm, the request.form collection uses the name="" property of the HTML form.
i.e. to include the contents of your textarea:
'Add the email body text
objCdoMessage.TextBody = "The following comment was submitted via the feedback form:" & Request.Form("Comments")
Related
I am moving this classic ASP app to AWS and using AWS SES SMTP to send site emails (automated, post registration email).
So, the code below works but when the email arrives it is truncated (incomplete)?
Mail Function:
Function Sendmail(Sender, Subject, Recipient, Body)
dim myMail, strServer
strServer = Request.ServerVariables("server_name")
if strServer <> "localhost" then
Set myMail=Server.CreateObject("CDO.Message")
myMail.Subject=Subject
myMail.From=Sender
myMail.To=Recipient
myMail.HTMLBody=Body
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="email-smtp.us-east-1.amazonaws.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=465
'requires authentication
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'username
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername")="a username"
'password
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword")="a password"
'startTLS
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl")=true
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
end if
End function
Mail Body
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'><html lang='en'><head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1258'> <meta name='viewport' content='width=device-width, initial-scale=1'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='format-detection' content='telephone=no'> <title>Title</title> <link rel='stylesheet' type='text/css' href='http://www.website.com/styles.css'> <link rel='stylesheet' type='text/css' href='http://www.website.com/responsive.css'></head><body style='margin:0; padding:0;' bgcolor='#F0F0F0' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'><table border='0' width='100%' height='100%' cellpadding='0' cellspacing='0' bgcolor='#F0F0F0'><tr><td align='center' valign='top' bgcolor='#F0F0F0' style='background-color: #F0F0F0;'> <br/> <table border='0' width='600' cellpadding='0' cellspacing='0' class='container'><tr><td class='header' align='left'><img src='http://www.website.com/images/email/logo_small_en.png'/> </td></tr><tr> <td class='container-padding content' align='left' bgcolor='#FFFFFF'> <br/><div class='title'>Welcome to the site! </div><br/><div class='body-text'> <p>Welcome to the website<div class='hr'></div><br/><div class='subtitle'>Have fun!</div><br/> </td></tr><tr> <td class='container-padding footer-text' align='left'><br/>© 2016 <br/> <br/>You are receiving this email because you registered for the website. Please click here to <a href=''>unsubscribe</a>. <br/> </td></tr></table></td></tr></table></body></html>
Truncated always at the same spot?
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'><html lang='en'><head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1258'> <meta name='viewport' content='width=device-width, initial-scale=1'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='format-detection' content='telephone=no'> <title>Title</title> <link rel='stylesheet' type='text/css' href='http://www.website.com/styles.css'> <link rel='stylesheet' type='text/css' href='http://www.website.com/responsive.css'></head><body style='margin:0; padding:0;' bgcolor='#F0F0F0' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'><table border='0' width='100%' height='100%' cellpadding='0' cellspacing='0' bgcolor='#F0F0F0'> <tr> <td align='center' valign='top' bgcolor='#F0F0F0' style='background-color: #F0F0F0;'> <br/> <table border='0' width='600' cellpadding='0' cellspacing='0' class='container'> <tr> <td class='he
I can't seem to track this down? Is the error in my function or the mail body? Is it an AWS limitation?
Thanks for your thoughts,
SMTP servers can throw a "Line too long" error when a line of the email exceeds some server-defined length. Since your message is always truncated at the same spot try inserting line breaks into your message body. I know AWS SES SMTP can return this error but I am unsure as to what the limit is. Here is a related conversation with a similar error and CDO for reference.
CDO uses 7bit for content transfer encoding by default, which does not truncate the long lines.
You don't need a user defined function but specify an appropriate content transfer encoding for the message body.
8bit, quoted-printable and base64 are standard transfer encodings will take care of the long lines.
'...
myMail.Configuration.Fields.Update
myMail.HTMLBodyPart.ContentTransferEncoding = "8bit"
myMail.Send
'...
I have spent a significant time looking for an answer, and tried every solution without success :/
Basically I want to use wamp server to create contact form that will be sent to my mail address.
I have wamp running but for the life of me I can't figure out why I wouldn't receive the mails, I either get the 404 page when submitting the form, or lately "Warning: mail(): SMTP server response: 553 sorry, that domain isn't in my list of allowed rcpthosts".
I am now looking for a solution that will at least send the form to my address, whether it's secured or not I just want to see an actual mail successfully sent.
Thanks !
edit: here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<div id="contact-area">
<form method="post" action="contactengine.php">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"> </textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</div>
</body>
</html>
--then the contact engine--
<?php
$EmailFrom = "myadress#mail.com";
$EmailTo = "myadress#mail.com";
$Subject = "Nice & Simple Contact Form by CSS-Tricks";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
--then the thanks message--
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<head>
<title>A Nice & Simple Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<img src="images/title.gif" alt="A Nice & Simple Contact Form" />
<p>By CSS-Tricks</p>
<br /><br />
<h1>Your message has been sent!</h1><br />
<p>Back to Contact Form</p>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-68528-29";
urchinTracker();
</script>
</body>
</html>
Windows does not come with a Mail Server so just calling mail() will work as far as php is concerned but the mail goes nowhere.
You either need to install a mail server or use something like the PHPMailer library to allow you to send SMTP mails via something like Yahoo or Google.
I will preface this by saying my background is Graphic Design (been doing JavaScript for a few years).Ok, I've been looking and looking for a simple tutorial on how to create a basic form with a a controller, that sends the form info in the body of an email.
This is what I have in my GSP:
<g:form name="batchform" url="[action:'forminfo', controller:'onboardingform'] />
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
<input type="submit" value="Submit Form" id="FormButton" >
<g:form>
And the controller is where I get confused:
package .com
import util.Environment
import MailTools
import MetricsLogger
class OnboardingformController {
String apparea01,
String deptname02
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
}
def index() {
render (view:'onboardingform.gsp')
}
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
}
I do not currently have a DOMAIN set up since there is no DB attached to this site. I just need to shove those Field Inputs into the Email body. I realize this maybe a very basic operation that escapes me (my background is Fine Arts, not Computer Science).
The MailTools is configured already to a default mailbox. The form needs to be send to another email address.
The MetricsLogger captures user info upon landing on the page.
Thanks in advance. This knowledge will open my eyes in my quest to be an Artist / Programmer :)
Ok, I came up with this controller in
grails-app/controllers/test/OnboardingformController.groovy:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( String apparea01, String deptname02, String email ) {
println "Send Mail from $email to me#email.com with apparea01=$apparea01 and deptname02=$deptname02"
/*
// Commented out for now so I don't have to set up mail ;-)
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
*/
redirect( action:'index' )
}
}
And this GSP grails-app/onboardingform/onboardingform.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:form action="formSubmission">
<p>
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
</p>
<p>
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
</p>
<p>
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${params.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</g:form>
</body>
</html>
Which when the form is filled in, should print out the values you entered (to the console) and redirect to the form. Let me know if anything doesn't make sense :-)
If you need validation (without a domain object), you can use a Command Object. This changes the controller to:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( SubmissionCommandObject cmd ) {
if( !cmd.validate() ) {
render( view: 'onboardingForm.gsp', model:[ data: cmd ] )
return
}
else {
println "Send Mail from $cmd.email to me#email.com with apparea01=$cmd.apparea01 and deptname02=$cmd.deptname02"
}
redirect( action:'index' )
}
}
class SubmissionCommandObject {
String apparea01
String deptname02
String email
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
email blank: false, email: true
}
}
And the view to:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:hasErrors bean="${data}">
<g:renderErrors bean="${data}" as="list" />
</g:hasErrors>
<g:form action="formSubmission">
<fieldset>
<p class="prop ${hasErrors(bean:data, field:'apparea01', 'errors')}">
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${data?.apparea01}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'deptname02', 'errors')}">
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${data?.deptname02}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'email', 'errors')}">
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${data?.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</fieldset>
</g:form>
</body>
</html>
Obviously, this could be prettier, but will suffice for this quick example
I am trying to send some values from a form to a responsebody for doing some actions on those values. But the values are not at all getting forwarded to that handler. i couldn't find a reason.
What could be the problem here?
My handler
#RequestMapping(value="/redemptionRedirect1/{userId}", method=RequestMethod.GET)
#ResponseBody
public Transaction submitRedemption(#PathVariable("userId") long userId,#RequestParam(value="amount") String amount1,#RequestParam("bankaccount") int bankaccount,#RequestParam("demataccount") int demataccount)
{
boolean flag;
Double amount=Double.parseDouble(amount1);
Transaction transaction=new Transaction();
transaction.setBankAccount(transactionService.getBank(bankaccount));
transaction.setDematAccount(transactionService.getDemat(demataccount));
transaction.setTransactionAmount(amount);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User user=userService.getUser(name);
transaction.setUser(user);
flag = transactionService.addRedemptionTransactions(transaction);
return transaction;
}
My JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="redemptionRedirect1/${user.userId}.htm" method="get">
<table>
<tr><td>Amount: </td><td><input id="amount" type="text" maxlength="5" value='<c:out value="${amount}"/>' placeholder='<c:out value="${amount}"/>'/></td></tr>
<tr><td>
Bank Accounts: </td><td><select id="bankaccount" >
<c:forEach items="${baccounts}" var="account">
<option value='<c:out value="${account.accountNumber}"/>'>
<c:out value="${account.name}"/>
</option>
</c:forEach>
</select>
</td></tr>
<tr><td>Demat Account: </td><td><input id="demataccount" type="text" placeholder='<c:out value="${daccount.dematName}"/>' value='<c:out value="${daccount.dematAccountNumber}"/>'/></td></tr>
<tr><td><input type="submit" value="Confirm"/></td></tr>
</table>
</form>
</body>
</html>
The form serializes itself via name attribute of every input.
So first you may run the developer tools feature of your browser and check if the values are added to the request or (this works only for GET requests) check if the values are added to the URL after the submit. If not - add the name attribute for every corresponding input.
I've tried several variations of ASP & PHP native & 3rd party mailer programs. I have hit a wall at almost every point between setting ini parameters from within the scripts to permission denied/transport fails.
I would be wasting time to show my examples for what I've tried so far. All my searches produce too many results with too many forums with too many 3rd party installations. I want to find the simplest way to set this up.
I don't care about fancy html formatting, attachments, colors, radio buttons, check boxes, etc... I would just love to find something with one text form field and a submit button that upon clicking it will send a simple email to me. I thought this would be a lot easier, but I never worked with IIS servers before.
A step by step approach or a link to a tested true resource would be greatly appreciated.
EDIT
The closest I got, with the least cryptic of error messages was with this asp code from tizag...
<%
'Sends an email
Dim mail
Set mail = Server.CreateObject("CDO.Message")
mail.To = Request.Form("To")
mail.From = Request.Form("From")
mail.Subject = Request.Form("Subject")
mail.TextBody = Request.Form("Body")
mail.Send()
Response.Write("Mail Sent!")
'Destroy the mail object!
Set mail = nothing
%>
The error I get back is:
CDO.Message.1 error '80040220'
The "SendUsing" configuration value is invalid.
For ASP.NET:
Install ASP.NET - I will assume that you have version 2, 3, or 3.5 of .NET installed.
In a command prompt:
cd \Windows\Microsoft.NET\Framework\v2.0.50727
aspnet_regiis.exe -i
Create a file in the appropriate virtual directory (maybe inetpub\wwwroot?) called email.aspx with the following text:
<%# Page language="c#" %>
<%# Import Namespace="System.Net.Mail" %>
<script runat="server">
protected void SendButton_Click(object sender, EventArgs e)
{
MailMessage message = new MailMessage(
"jane#contoso.com",
FromEmail.Text,
Subject.Text,
Message.Text);
SmtpClient client = new SmtpClient("127.0.0.1");
client.Send(message);
}
</script>
<html>
<body>
<form runat="server">
<table>
<tr>
<td>From Email:</td>
<td><asp:TextBox id="FromEmail" runat="server" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox id="Subject" runat="server" /></td>
</tr>
<tr>
<td>Message:</td>
<td><asp:TextBox id="Message" runat="server" TextMode="MultiLine" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button id="SendButton" runat="Server" Text="Send" OnClick="SendButton_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
You will need to change the string "127.0.0.1" to the IP address of your SMTP server and you will need to change the "jane#contoso.com" to the email address that you would like the mail sent to.
You could also require that the user enters an email address (and a valid one), a subject, and a message, by adding RequiredFieldValidator's and a RegularExpressionValidator.
Sending email in ASP using the CDO.Message object is really easy.
Here's a more complex sample with error handling and email address validation.
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit %>
<%
Dim bPostback : bPostback = request.ServerVariables("REQUEST_METHOD") = "POST"
Dim sResult : sResult = ""
If bPostBack Then
Dim sSmtpServer : sSmtpServer = "your.smtp.server"
Dim sToEmail : sToEmail = "youremail#yourdomain.com"
Dim sFromEmail : sFromEmail = request.Form("email")
Dim sName : sName = request.Form("name")
Dim sSubject : sSubject = request.Form("subject")
Dim sBody : sBody = request.Form("body")
Dim oEmailer : Set oEmailer = New Emailer
oEmailer.SmtpServer = sSmtpServer
oEmailer.FromEmail = sFromEmail
oEmailer.ToEmail = sToEmail
oEmailer.Subject = sSubject
'oEmailer.HTMLBody = ""
oEmailer.TextBody = sBody
If oEmailer.sendEmail Then
sResult = "Email sent!"
Else
sResult = "Something went terribly wrong!(" + oEmailer.ErrMsg + ")"
End If
End If
'Simple Emailer
Class Emailer
Private oCDOM
Public FromEmail
Public ToEmail
Public Subject
Public HTMLBody
Public TextBody
Public SmtpServer
Public Port
Public ErrMsg
Private Sub Class_Initialize()
Set oCDOM = Server.CreateObject("CDO.Message")
TextBody = ""
'HTMLBody = ""
Port = 25
End Sub
'SQL IsNull equivalent
Private Function ifNull(vVar1, vVar2)
If Not IsNull(vVar1) Then
ifNull = vVar1
Else
ifNull = vVar2
End If
End Function
'Verifies that the Email address conforms to RFC standard.
Public Function isEmail(emailStr)
isEmail = False
If IsNull(emailStr) Then Exit Function
Dim emailPat : emailPat = "^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*#((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$"
Dim loRE : Set loRE = New RegExp
loRE.IgnoreCase = True
loRE.Global = True
loRE.Pattern = emailPat
If loRE.Test(emailStr) Then isEmail = True
Set loRE = Nothing
End Function
Public Function sendEmail()
sendEmail = True
'On Error Resume Next
If IfNull(SmtpServer,"") = "" Then sendEmail = False
If Not isEmail(FromEmail) Then sendEmail = False
If Not isEmail(ToEmail) Then sendEmail = False
If IfNull(Trim(Subject),"") = "" Then sendEmail = False
If IfNull(Trim(HTMLBody),"") = "" And IfNull(Trim(TextBody),"") = "" Then sendEmail = False
If sendEmail = False Then Exit Function
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")=SmtpServer
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=CINT(Port)
oCDOM.Configuration.Fields.Update
oCDOM.From = FromEmail
oCDOM.To = ToEmail
oCDOM.Subject = Subject
'oCDOM.HTMLBody = "<div>" & HTMLBody & "<div>"
oCDOM.TextBody = TextBody
oCDOM.Send
If Err.Number <> 0 Then
ErrMsg = Err.description
Err.Clear
sendEmail = False
Exit Function
Else
sendEmail = True
Exit Function
End If
End Function
Private Sub Class_Terminate()
Set oCDOM = Nothing
End Sub
End Class
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Emailer</title>
</head>
<body>
<p><strong><%=sResult%></strong></p>
<form action="" method="post" target="_self">
<label for="name">Name:</label><input id="name" name="name" type="text" size="50" maxlength="50" />
<br />
<label for="email">Email:</label><input id="email" name="email" type="text" size="50" maxlength="1024" />
<br />
<label for="subject">Subject:</label><input id="subject" name="subject" type="text" size="50" maxlength="1024" />
<br />
<label for="body">Body:</label>
<br />
<textarea id="body" name="body"></textarea>
<br />
<input name="Submit" value="Submit" type="submit" />
</form>
</body>
</html>
PHP:
use the builtin mail (...) method. If your not doing anything fancy you can use it directly.
Example:
form.php
<?php
if($_REQUEST['action']=='mail'){
$to="toaddress#gmail.com";
$from="fromaddress#gmail.com";
$subject="this is my subject";
$body=$_POST['body'];
$headers="From: $from\r\nTo: $to\r\nSubject: $subject\r\n";
if (stristr($to,"Content-Type")||stristr($subject,"Content-Type")||stristr($body,"Content-Type")||stristr($headers,"Content-Type")) {
header("HTTP/1.0 403 Forbidden");
echo "YOU HAVE BEEN BANNED FROM ACCESSING THIS SERVER FOR TRIGGERING OUR SPAMMER TRAP";
exit;
}
if(mail($to,$subject,$body,$headers)){
echo("Succesfully mailed to $to");
exit();
}else{
echo("Failed to send mail<br>");
}
}
?>
<form method=post>
<input type=hidden name=action value=mail>
<textarea name=body rows=4 cols=40><?php echo($_POST['body']); ?></textarea>
<input type=submit value=Send>
</form>
PS: The Content-Type check is to prevent someone from hijacking your email form.
PSS: This will use the mailserver as set in php.ini, that is the only setting that should matter.
For your ASP example, I think you are just missing the smtp server configuration:
<%
'Sends an email
Dim mail
Set mail = Server.CreateObject("CDO.Message")
mail.To = Request.Form("To")
mail.From = Request.Form("From")
mail.Subject = Request.Form("Subject")
mail.TextBody = Request.Form("Body")
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'Server port
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
mail.Configuration.Fields.Update
mail.Send()
Response.Write("Mail Sent!")
'Destroy the mail object!
Set mail = nothing
%>
As in the ASP.NET example, you would need to change "smtp.server.com" to your SMTP server's IP address.
This work for me using ASP Classic: http://www.powerasp.net/content/new/sending_email_cdosys.asp
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")
'This section provides the configuration information for the remote SMTP server.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="remoteserver"
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
ObjSendMail.Configuration.Fields.Update
'End remote SMTP server configuration section==
ObjSendMail.To = "test#test.com"
ObjSendMail.Subject = "this is the subject"
ObjSendMail.From = "someone#someone.net"
' we are sending a text email.. simply switch the comments around to send an html email instead
'ObjSendMail.HTMLBody = "this is the body"
ObjSendMail.TextBody = "this is the body"
ObjSendMail.Send
Set ObjSendMail = Nothing