Send automatic email SSL Implicit ASP.NET VB - asp.net

this code is inside a "for next" loop and sends an email through an implicit SSL server.
Last week I had to change the smtp server and now this new smtp server has a block that does not allow simultaneous connection to more than 5 users.
If the for loop sends more than 5 emails I get the error "Too many simultaneous connections".
I think this occurs because the emails are sent in a NON ASYNCHRONOUS way and consequently the sending of the email takes too long.
I would like to ask if it is possible to use CDO.message ASYNCHRONOUSLY or if you can recommend another code that sends emails synchronously using an implicit SSL server.
Thank you
Dim objEmail = CreateObject("CDO.Message")
Dim objConf = objEmail.Configuration
Dim objFlds = objConf.Fields
With objFlds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = mailServer
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPport
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = cdoTimeout
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasicAuth
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = mailusername
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = mailpassword
.Update()
End With
objEmail.To = email_cli
objEmail.From = ConfigurationManager.AppSettings("p_email")
objEmail.Subject = mailOggetto
objEmail.HTMLBody = testo_email
Try
objEmail.Send()
Catch ex As Exception
FailureText.Text = ex.Message
Exit Sub
Finally
objEmail = Nothing
objConf = Nothing
objFlds = Nothing
End Try

Related

Unable to send email with IIS7

I'm migrating a website from IIS6 to IIS7. I have everything working but the site will not send emails.
I have confirmed that the server is handling emails correctly, because when I drop a text document into the pickup folder it is delivered, but when I try to send a message via code I either get an error or just nothing.
The SMTP virtual server is setup with standard settings.
The website in question is using 4.0 Framework, Integrated Application pool, I've tried both the ApplicationPoolIdentity, and the NetworkService with no effect. For the site's SMTP module I've tried an SMTP server of 127.0.0.1, localhost and the server's domain name, all on port 25.
For testing I've been using VBS and classic asp to send an email as well as asp.net.
I've been trying very basic scripts copied off the internet where all the comments say that it works. For example
vb.net. This code shows no error, but no message is sent and I've found nothing in the event viewer
Public Shared errorEmailTo As String = System.Configuration.ConfigurationManager.AppSettings("errorEmailTo")
Public Shared errorEmailFrom As String = System.Configuration.ConfigurationManager.AppSettings("errorEmailFrom")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim email As String = "This is a test email."
show.Text = "To: " + System.Configuration.ConfigurationManager.AppSettings("errorEmailTo") + "<br/>"
show.Text += "From: " + System.Configuration.ConfigurationManager.AppSettings("errorEmailFrom") + "<br/>"
Try
Helper.SendError(email)
show.Text += "No Error"
Catch ex As Exception
show.Text += "Error: " + ex.Message
End Try
End Sub
Public Shared Sub SendError(ByVal strBody As String)
Dim Email As New System.Net.Mail.MailMessage(errorEmailFrom, errorEmailTo)
Email.Subject = "Error Message"
Email.Body = strBody
Dim mailClient As New System.Net.Mail.SmtpClient()
mailClient.UseDefaultCredentials = True
mailClient.EnableSsl = False
Try
mailClient.Send(Email)
Catch ex As Exception
End Try
End Sub
VBS. This code returns the error "The transport failed to connect to the server." For which I've not found anything other than a new nearly identical code block
strSMTPFrom = "donotreply#here.com"
strSMTPTo = "me#here.com"
strSMTPRelay = "localhost"
strTextBody = "Body of your email"
strSubject = "Subject line"
Set oMessage = CreateObject("CDO.Message")
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPRelay
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update
oMessage.Subject = strSubject
oMessage.From = strSMTPFrom
oMessage.To = strSMTPTo
oMessage.TextBody = strTextBody
oMessage.Send
Classic ASP gives the same error message.
<%
Dim sch, cdoConfig, cdoMessage
sch = "http://schemas.microsoft.com/cdo/configuration/"
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(sch & "sendusing") = 2 ' cdoSendUsingPort
.Item(sch & "smtpserver") = "localhost"
.Item(sch & "smtpserverport") = 25
.update
End With
Set cdoMessage = CreateObject("CDO.Message")
With cdoMessage
Set .Configuration = cdoConfig
.From = "donotreply#here.com"
.To = "me#here.com"
.Subject = "Email test"
.TextBody = "This is the test body of the email"
.Send
End With
Set cdoMessage = Nothing
Set cdoConfig = Nothing
%>
I've found example after example that give these code blocks as working examples, what am I doing wrong?
Brought in a fresh pair of eyes, and we found the answer.
The virtual SMTP server was listening on port 465(SSL), not 25. So with that corrected, classic ASP and VBS worked, but not VB.Net. We created a new Virtual SMTP server, listening on port 587. And as long as VB.Net had SSL disabled it would work. It appears that the new server didn't receive the SSL certificate during migration.

Problems With Paypal Express Checkout Integration (WEBREQUEST)

So I was struggling with making head or tail out of the PayPal documentation and always felt that something was not right with my Webrequest.
So I stripped all the code back to basic and simply submitted the request via HTTP and the PLUS side is that I now get a response back from the PayPal sandbox server where ACK=Success and TOKEN=Valid-token-value-here there are some other variables returned too, such as CORRELATIONID and TIMESTAMP.
And hence so I tried some of the webrequest samples and I simply get a blank screen instead of being redirected to Paypal for the (sandbox) customer to complete payment.
So if anyone can post their WebRequest method that would be great.
Here is the code I used for my webrequest, I'm sure its wrong but cannot pinpoint where it is going wrong.
Also, when I run the code on my localhost during debugging, everything works fine and the call is completed with SUCCESS and a TOKEN is received.
When I run it live, I recieve Error Number 5 in the Error exception and also the text `Remote host failed to connect' in the STATUS DESCRIPTION.
THIS IS THE UPDATED CODE
Function MakeWebRequest(ByVal pUseSandbox As Boolean, ByVal pRequestMethod As String, ByVal pReturnUrl As String, ByVal pCancelUrl As String, ByRef pRtnStatus As String, ByRef pRtnStatusId As HttpStatusCode, ByRef pRtnResponseString As String) As Boolean
'
Dim _sxHost As String = Nothing
Dim _sxEndpoint As String = Nothing
Dim _sxNameValCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxResponseCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxCounta As Integer = Nothing
Dim _sxParamsString As String = Nothing
'
'-> Init
_sxParamsString = ""
MakeWebRequest = False
_sxNameValCol = New System.Collections.Specialized.NameValueCollection()
_sxResponseCol = New System.Collections.Specialized.NameValueCollection()
If pUseSandbox Then
_sxHost = "http://www.sandbox.paypal.com"
_sxEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
Else
_sxHost = "http://www.paypal.com"
_sxEndpoint = "https://api-3t.paypal.com/nvp"
End If
'-> Create Request
Try
'-> Key/Value Collection Params
_sxNameValCol.Add("METHOD", "SetExpressCheckout")
_sxNameValCol.Add("USER", _UserName)
_sxNameValCol.Add("PWD", _Password)
_sxNameValCol.Add("SIGNATURE", _Signature)
_sxNameValCol.Add("PAYMENTREQUEST_0_AMT", Format(_Basket.BasketTotalIncDelivery / 100, "0.00"))
_sxNameValCol.Add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale")
_sxNameValCol.Add("PAYMENTREQUEST_0_CURRENCYCODE", "GBP")
_sxNameValCol.Add("RETURNURL", pReturnUrl)
_sxNameValCol.Add("CANCELURL", pCancelUrl)
_sxNameValCol.Add("REQCONFIRMSHIPPING", "0")
_sxNameValCol.Add("NOSHIPPING", "2")
_sxNameValCol.Add("LOCALECODE", "EN")
_sxNameValCol.Add("BUTTONSOURCE", "PP-ECWizard")
_sxNameValCol.Add("VERSION", "93.0")
'-> UrlEncode
For _sxCounta = 0 To _sxNameValCol.Count - 1
If _sxCounta = 0 Then
_sxParamsString = _sxParamsString & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
Else
_sxParamsString = _sxParamsString & "&" & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
End If
Next
'-> Credentials (not used)
'_sxRequest.Credentials = CredentialCache.DefaultCredentials
Try
Dim _sxRequest As WebRequest = DirectCast(System.Net.WebRequest.Create(_sxEndpoint), System.Net.HttpWebRequest)
'-> Convert request to byte-array
Dim _sxByteArray As Byte() = Encoding.UTF8.GetBytes(_sxParamsString)
_sxRequest.Method = "POST" 'Our method is post, otherwise the buffer (_sxParamsString) would be useless
_sxRequest.ContentType = "application/x-www-form-urlencoded" 'We use form contentType, for the postvars
_sxRequest.ContentLength = _sxByteArray.Length 'The length of the buffer (postvars) is used as contentlength
Dim _sxPostDataStream As System.IO.Stream = _sxRequest.GetRequestStream() 'We open a stream for writing the postvars
_sxPostDataStream.Write(_sxByteArray, 0, _sxByteArray.Length) 'Now we write, and afterwards, we close
_sxPostDataStream.Close() 'Closing is always important!
'-> Create Response
Dim _sxResponse As HttpWebResponse = DirectCast(_sxRequest.GetResponse(), HttpWebResponse)
'-> Get Response Status
pRtnStatus = _sxResponse.StatusDescription
pRtnStatusId = _sxResponse.StatusCode
'-> Reponse Stream
Dim _sxResponseStream As Stream = _sxResponse.GetResponseStream() 'Open a stream to the response
'-> Response Stream Reader
Dim _sxStreamReader As New StreamReader(_sxResponseStream) 'Open as reader for the stream
pRtnResponseString = _sxStreamReader.ReadToEnd() 'Read the response string
MakeWebRequest = True
'-> Tidy up
_sxStreamReader.Close()
_sxResponseStream.Close()
_sxResponse.Close()
_sxByteArray = Nothing
_sxPostDataStream = Nothing
_sxRequest = Nothing
_sxResponse = Nothing
_sxResponseStream = Nothing
_sxStreamReader = Nothing
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "response(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "request(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
'-> Tidy Up
_sxHost = Nothing
_sxEndpoint = Nothing
_sxNameValCol = Nothing
_sxResponseCol = Nothing
_sxCounta = Nothing
_sxParamsString = Nothing
'
End Function
OK, so it's now clear that you're not getting any response from the server because your server isn't able to connect to PayPal's servers at all. Hence, you got no server-response and the message Unable to connect to the remote server. When I tested, I got a HTTP 200 response with the following body:
TIMESTAMP=2015-07-07T09:07:39Z&CORRELATIONID=7f4d2313c9696&ACK=Failure&VERSION=93.0&BUILD=17276661&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
Obviously that's because I tested with a blank username and password.
So, something is wrong with your server setup that's preventing you from making outside connections, either at the IIS level or due to your firewall configuration.
Without physically being present at your machine, there's not a lot we can do to track down what's blocking it, but you can try opening HTTP requests to other public websites like Google.com and see if those succeed.

smtp clients `SendAsync()` method

Protected Sub btnLocalSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLocalSubmit.Click
Dim logic = New connections
logic.emailsToSend(User.Identity.Name, getURL, reportedBy)
SendAsync()
Response.Redirect(getRedirectionPath, False)
Catch ex As Exception
Response.Write(ex.Message)
Finally
_con.Close()
_con.Dispose()
_sqlComm.Dispose()
End Try
End Sub
Sub SendAsync()
Dim _con As New SqlConnection(ConfigurationManager.ConnectionStrings("CitizenJDBConnectionString").ConnectionString)
Dim _sqlDataAdapter As New SqlDataAdapter("SELECT * FROM EmailSender", _con)
Dim _table As New System.Data.DataTable
Try
_con.Open()
_sqlDataAdapter.Fill(_table)
_con.Close()
For i As Integer = 0 To _table.Rows.Count - 1
Dim AppPath As String = Request.PhysicalApplicationPath
Dim sr As New StreamReader(AppPath & "EmailTemplates/NewReport.txt")
Dim message As New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("admin#xxxx.com")
message.To.Add(New MailAddress(_table.Rows(i).Item(1)))
message.Subject = "New User registration !"
message.Body = sr.ReadToEnd()
sr.Close()
message.Body = message.Body.Replace("<%ReporterName%>", _table.Rows(i).Item(3))
message.Body = message.Body.Replace("<%ReportURL%>", _table.Rows(i).Item(2))
Dim client As New SmtpClient()
client.Host = "smtp.xxxxx.com"
'smtp.gmail.com
client.Port = 25
client.UseDefaultCredentials = True
client.Credentials = New System.Net.NetworkCredential("admin#xxxx.com", "123456")
'client.EnableSsl = True
Dim userState As Object = message
'wire up the event for when the Async send is completed
AddHandler client.SendCompleted, AddressOf SmtpClient_OnCompleted
client.SendAsync(message, userState)
Next
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub 'SendAsync
Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
'Get the Original MailMessage object
Dim message As MailMessage = CType(e.UserState, MailMessage)
'write out the subject
Dim subject As String = message.Subject
If e.Cancelled Then
Console.WriteLine("Send canceled for mail with subject [{0}].", subject)
End If
If Not (e.Error Is Nothing) Then
Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString())
Else
Console.WriteLine("Message [{0}] sent.", subject)
End If
End Sub 'SmtpClient_OnCompleted
I am using the smtp clients SendAsync() function to send out emails asynchronously...but this function does not work ...why?? i do not get any email..when i send it Synchronously...i get the emails, this means my settings are correct...so what is wrong with the SendAsync() method??
I do this all the time, and after years of doing this I suggest a (2) fold solution to your problem:
Refactor the actual sending email code (System.Net stuff) into a WCF service or separate .dll (I prefer the service).
Continue to use your asynchronous delegate call from your ASP.NET page but do so in a 'fire-and-forget' manner where you do not wire up any callbacks.
You might say you need to know if something went wrong with sending the email. Let the WCF service that sends the emails handle this. Do any logging in the service. After all that's all you were really doing anyways was logging. If you need to get fancier with a workflow if the email fails, there are ways that your ASP.NET can be flagged, but I think you will find that once the service to send the emails is stable, you will have very few problems.
In fact I have been doing this exact method for years using a service called by ASP.NET to send emails and have sent 10 of thousands of differing emails and never had any problem with this fire-and-forget design.
And lastly, setting the page Async=True makes the page act overall synchronously in the end by blocking the main thread until all asynchronous process are completed. This can make the pages very slow to load and is typically not desired.

Sending email through CDOSYS but written in C#

I am sick and tired of my hosting company. I think you can help me here.
I have simple need that I have my complete website written in Classic ASP. Now I want to have a page which sends email using CDOSYS. I wanted to have that script in ASP from my hosting company that what setting should i have. They always send me code in C#.
here is they send always:
CDOSYS is part of the System.Web.Mail namespace and is installed by default on Windows 2000 and Windows XP platforms. It replaces CDONTS for sending SMTP email messages and can be used with our IIS 6 and IIS 7 Windows hosting accounts. The following code sample demonstrates how to create, format, and send email.
private void SendEmail()
{
const string SERVER = "relay-hosting.secureserver.net";
MailMessage oMail = new System.Web.Mail.MailMessage();
oMail.From = "emailaddress#domainname";
oMail.To = "emailaddress#domainname";
oMail.Subject = "Test email subject";
oMail.BodyFormat = MailFormat.Html; // enumeration
oMail.Priority = MailPriority.High; // enumeration
oMail.Body = "Sent at: " + DateTime.Now;
SmtpMail.SmtpServer = SERVER;
SmtpMail.Send(oMail);
oMail = null; // free up resources
}
Here is my ASP which I written to use same thing but doesn't work:
Set objCDOSYSMail = Server.CreateObject("CDO.Message")
Set objCDOSYSCon = Server.CreateObject ("CDO.Configuration")
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "relay-hosting.secureserver.net"
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objCDOSYSCon.Fields.Update
With objCDOSYSMail
.To = strEmail
.BCc = "a#gmail.com"
.Cc = "b#gmail.com"
.From = "sales#b.com"
.Subject = "Thank you!"
.HTMLBody = "Hello<br></br><h3>Thank you for your enquiry. <br/>"
Set objCDOSYSMail = Nothing
Set objCDOSYSCon = Nothing
I don't know how to use their code.... please help
You can use the following code in a classic ASP page to send email with CDOSYS:
Set objMail = Server.CreateObject("CDO.Message")
Set objConf = Server.CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing

cdonts and relay server?

I use CDONTS when I need to send up send email form on websites. Recently changed my hosting company to godaddy. I realized my send email form gives "permission denied" error. I called GoDaddy support. They told me I should use relay server "relay-hosting.secureserver.net" in my codes. I thought relay server used only with CDO.
How can I include it to my codes?
My codes
Set objEmail = Server.CreateObject("CDONTS.NewMail")
objEmail.To = MailTo
objEmail.Cc = MailCc
objEmail.From = MailFrom
objEmail.Subject = MailSubject
objEmail.Body = MailBody
objEmail.Send
Set objEmail = nothing
A web search for "cdonts relay" yielded this example which relates directly to your issue with GoDaddy.com - Based on everything I've read, this only works with CDO.Message instead of CDONTS.NewMail.
UPDATE: Here's the modified code
Set objMail = Server.CreateObject("CDO.Message")
objMail.From = MailFrom
objMail.To= MailTo
objMail.Subject = MailSubject
objMail.TextBody = MailBody
objMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "relay-hosting.secureserver.net"
objMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMail.Configuration.Fields.Update
objMail.Send
set ojbMail = nothing

Resources