How can I post my data onto the server? - c#

I am developing wp8 app. My question is that, The app is getting an error when I click on the registration button and the following exception occurred and the code is not going below string post data
An exception of type System.UnauthorizedAccessException occurred in System.Windows.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely continue
namespace docapp
{
public partial class registration : PhoneApplicationPage
{
public static string DeviceIDAsString;
public registration()
{
InitializeComponent();
//selction.Items.Add("india");
//selction.Items.Add("pakistan");
//selction.Items.Add("china");
//selction.Items.Add("USA");
String[] name = { "india", "china", "pakistan" };
String[] uname = { "Delhi", "Bijing", "Karachi" };
String[] university = { "AIIMS", "MDU", "PGI" };
String[] yeardate = { "2011", "2012", "2013" };
string[] question = { "what is your pet name", "what is your childhood name", "what is your mother name" };
this.country.ItemsSource = name;
this.city.ItemsSource = uname;
this.university.ItemsSource = university;
this.year.ItemsSource = yeardate;
this.question.ItemsSource = question;
}
private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (txtusername.Text == "")
{
MessageBox.Show("enter the name");
}
else if (txtid.Text == "")
{
MessageBox.Show("enter valid id");
}
else if (txtpassword.Password == "")
{
MessageBox.Show("enter the password");
}
else if (txtconfirm.Password == "")
{
MessageBox.Show("enter the same password again ");
}
else if (txtemail.Text == "")
{
MessageBox.Show("enter the valid email id ");
}
else if (txtmobileno.Text == "")
{
MessageBox.Show("enter the valid 10 digit mobile no ");
}
if (txtpassword.Password != txtconfirm.Password)
{
MessageBox.Show("password doesnot match please enter same password");
}
SendPost();
//getDeviceId();
}
//private static String getDeviceId()
//{
// //byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
// //return BitConverter.ToString(id).Replace("-", string.Empty);
// // get the unique device id for the publisher per device
//}
void SendPost()
{
byte[] myDeviceID = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
DeviceIDAsString = Convert.ToBase64String(myDeviceID);
Uri url = new Uri(" http://www.mobileoid2.co/docbase/index.php?methodname=createuser");
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Headers["username"] = txtusername.Text;
webRequest.Headers["userid"] = txtid.Text;
webRequest.Headers["password"] = txtpassword.Password;
webRequest.Headers["confirmpaswword"] = txtconfirm.Password;
webRequest.Headers["email"] = txtemail.Text;
webRequest.Headers["mobileno"] = txtmobileno.Text;
webRequest.Headers["country"] = country.SelectedItem.ToString();
webRequest.Headers["city"] = city.SelectedItem.ToString();
webRequest.Headers["university"] = university.SelectedItem.ToString();
webRequest.Headers["year"] = year.SelectedItem.ToString();
webRequest.Headers["question"] = question.SelectedItem.ToString();
webRequest.Headers["uniqueid"] = DeviceIDAsString;
webRequest.ContentType = "application/json;charset=utf-8";
//"text/json";//
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "username" + txtusername.Text + ".userid" + txtid.Text + "." + ".password" + txtpassword.Password + "." + ".confirmpassword" + txtconfirm.Password + "." + ".email" + txtemail.Text + "." + ".mobileno" + txtmobileno.Text + "." + "." + ".country" + country.SelectedItem.ToString() + "." + "." + ".city" + city.SelectedItem.ToString() + "." + "." + ".university" + university.SelectedItem.ToString() + "." + "." + ".year" + year.SelectedItem.ToString() + "." + ".question" + question.SelectedItem.ToString() + "." + ".uniqueid" + DeviceIDAsString +".";
var input = JsonConvert.SerializeObject(postData);
byte[] byteArray = Encoding.UTF8.GetBytes(input);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
//outputbox.Text = Response.ToString();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/docapp;component/login.xaml", UriKind.RelativeOrAbsolute));
}
}
}

Not sure why, but this error is generally thrown when the access is not allowed. Maybe the credentials you are trying to use are not allowed!
The issue is that the OS is denying the request due to I/O error, where the credentials are required, or you either don't have permission to read/write there, or the server needs a username/password match to allow you. Something like that. Try catching it using
try {
// code here to try..
} catch (System.UnauthorizedAccessException e) {
// error e.Message
}
Here is a Remark from the MSDN blog post:
An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property.
For More: http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception(v=vs.110).aspx

Related

Getting all phone numbers stored in the database using foreach loop in asp.net mvc

I have phone numbers stored in the database, I want to retrieve all phone numbers using foreach loop and assign them to variable and send bulk sms, but problem is, I am getting only one number from database. Here is my code:
// GET: Members/SendBatch
public ActionResult SendBatch()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendBatch(Membership member)
{
var db = new ChurchContext();
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
}
}
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
return View("Index", member);
}
public static string GetMinisry(string ministry)
{
string membership = "";
switch (ministry)
{
case "Youth":
membership = "Youth";
break;
case "Children":
membership = "Children";
break;
case "Men":
membership = "Men";
break;
case "Women":
membership = "Women";
break;
case "Visitors":
membership = "Visitors";
break;
case "Members":
membership = "Members";
break;
}
return membership;
}
I would like to get all the phone numbers and assigned them to cell variable and then to sms api and send bulk sms.
Try this (dirty but will do the job):
string mess = member.Message;
string cell = member.Cell;
List<string> cellNumbers = new List<string>(); //LIST OF NUMBERs
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
cellNumbers.add(cell);
}
}
foreach(string number in cellNumbers) // send all the sms
{
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + number;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
You have a cycle where you override cell in each iteration and even though cell received all the values you need, all were overriden by the next one, except for the very last one. When the cycle is finished, you are sending the request using the very last value of cell. This is why you had the illusion that you have got a single value. Actually you have got all the values, but made the mistake of overriding them before using them. The solution is to send the request inside the cycle instead of after the cycle, like this:
// GET: Members/SendBatch
public ActionResult SendBatch()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendBatch(Membership member)
{
var db = new ChurchContext();
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
return View("Index", member);
}
}
}
public static string GetMinisry(string ministry)
{
string membership = "";
switch (ministry)
{
case "Youth":
membership = "Youth";
break;
case "Children":
membership = "Children";
break;
case "Men":
membership = "Men";
break;
case "Women":
membership = "Women";
break;
case "Visitors":
membership = "Visitors";
break;
case "Members":
membership = "Members";
break;
}
return membership;
}
Thanks guys, your answers solved my problem, hope future visitors to this page with similar problem will get help quickly.

Windows service calling WebGet method returns 400 error

I have a service that runs a c# method to sync a database with active directory at a specified interval. This code has worked in a test environment and now putting it on a different server it is returning the following message:
The server encountered an error processing the request. Please see the
service help page for constructing valid requests to the service.
The help page looks like this:
But the "SyncActiveDirectory" URI is giving me this error:
This is a new server. Maybe i am missing something that needs to be installed or a setting in IIS? Any help would be much appreciated.
EDIT:
Here is the method that called the webget:
private void SyncActiveDirectoryServiceCall()
{
WriteIntoLogFile("Start _schedulerService.SyncActiveDirectoryServiceCall()");
try
{
var reader = new AppSettingsReader();
var serviceurl = reader.GetValue("ServiceUrl", typeof(string));
var client = new RestSharp.RestClient(serviceurl.ToString());
var request = new RestSharp.RestRequest("SyncActiveDirectory", RestSharp.Method.GET);
var response = client.Execute(request);
WriteIntoLogFile(response.Content);
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
WriteIntoLogFile("Error code: " + httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
WriteIntoLogFile("STREAMED: " + text);
}
}
WriteIntoLogFile("TRY-CATCH: " + ex.ToString());
}
WriteIntoLogFile("End _schedulerService.SyncActiveDirectoryServiceCall()");
}
And here is the method being called:
namespace SyncActiveDirectory
{
public class SyncLocalWithLDAP : ISyncLocalWithLDAP
{
private List<GenericUser> users { get; set; }
private List<GenericUser> roles { get; set; }
[WebGet(UriTemplate = "SyncActiveDirectory")]
public void SyncActiveDirectory()
{
string constr = GetConnectionStringValue("ProteusMMXCustomerDB");
string usr = GetAppsettingValue("ldap_login_username");
string pss = GetAppsettingValue("ldap_login_password");
string filePath = string.Empty;
ActiveDirectoryWrapper wrapper = new ActiveDirectoryWrapper();
if (!Directory.Exists(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog"))
{
Directory.CreateDirectory(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog");
}
if (!File.Exists(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + "/" + "SyncLog.txt"))
{
File.Create(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + "/" + "SyncLog.txt").Dispose();
}
filePath = WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + #"\" + "SyncLog.txt";
using (StreamWriter w = File.AppendText(filePath))
{
Log("Constr - " + constr + " , u - " + usr + " p - " + pss, w);
try
{
Log("Start sync outer", w);
SyncLocalWithLDAP_Users_Roles(constr, usr, pss, w);
Log("End sync outer", w);
}
catch (Exception ex)
{
Log("Error: " + ex.Message, w);
}
}
}
EDIT:
Pic of htm file added to that directory.
EDIT:
If this helps here is Chrome Developer Tools headers:

Why does a method that calls Ping.Send() on an invalid URL die with an unhandled exception?

The following method calls Ping.Send(). When I pass an invalid URL, Send() dies and an unhandled exception happens. What is the cause of this?
private void ping()
{
comboBox3.Visible = false;
listBox2.Items.Clear();
// check the url if it is null
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
{
listBox2.Items.Add("Please use valid IP or web address!!");
comboBox3.Visible = false;
coloring_red_tab4();
}
else
{
// do the ping
coloring_green_tab4();
for (int i = 0; i < numericUpDown1.Value; i++)
{
string s;
s = textBox1.Text;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
Ping p = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
//pingexception was unhalded (if the url wrong here is the error)
PingReply r = p.Send(s, timeout, buffer, options);
// if it's true url
if (r.Status == IPStatus.Success)
{
listBox2.Items.Add("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n");
label91.Text = r.Address.ToString();
}
else
{
// just to know the ip for the website if they block the icmp protocol
listBox2.Items.Add(r.Status);
IPAddress[] ips;
ips = Dns.GetHostAddresses(textBox1.Text);
foreach (IPAddress ip in ips)
{
label91.Text = ip.ToString();
}
}
}
}
}
The exception is unhandled because you do not handle it. Whenever you call a .Net library method, you need to check its documentation to see what exceptions it throws, and decide which, if any, you want to handle at that level of code. Here is the relevant portion of the documentation for Ping.Send(), which I am including as an image so you will be able to recognize these sections going forward:
Notice that the documentation states that a PingException can occur if
An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.
Thus it's clear from the documentation that many errors from Ping() will be reported as thrown exceptions rather than reported by setting PingReply.Status != IPStatus.Success. So you need to modify your code to be something like the following:
public static bool TryPing(string hostNameOrAddress, out string pingStatusMessage, out string pingAddressMessage)
{
if (String.IsNullOrWhiteSpace(hostNameOrAddress))
{
pingStatusMessage = "Missing host name";
pingAddressMessage = "";
return false;
}
var data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
var buffer = Encoding.ASCII.GetBytes(data);
var timeout = 120;
using (var p = new Ping())
{
var options = new PingOptions();
options.DontFragment = true;
try
{
var r = p.Send(hostNameOrAddress, timeout, buffer, options);
if (r.Status == IPStatus.Success)
{
pingStatusMessage = "Ping to " + hostNameOrAddress.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n";
pingAddressMessage = r.Address.ToString();
return true;
}
else
{
// just to know the ip for the website if they block the icmp protocol
pingStatusMessage = r.Status.ToString();
var ips = Dns.GetHostAddresses(hostNameOrAddress);
pingAddressMessage = String.Join(",", ips.Select(ip => ip.ToString()));
return false;
}
}
catch (PingException ex)
{
pingStatusMessage = string.Format("Error pinging {0}: {1}", hostNameOrAddress, (ex.InnerException ?? ex).Message);
pingAddressMessage = hostNameOrAddress;
return false;
}
}
}
Here I have extracted a utility method from the user interface code and also properly disposed of the Ping instance after it is no longer needed.
Then
TryPing(#"www.google.com", out pingStatusMessage, out pingAddressMessage);
Gives
Ping to www.google.com[146.115.8.83] (Successful) Bytes =32 TTL=62 Response delay = 8 ms
While
TryPing(#"www.kdjf98rglkfgjldkfjgdl;fge8org.com", out pingStatusMessage, out pingAddressMessage);
Gives
Error pinging www.kdjf98rglkfgjldkfjgdl;fge8org.com: No such host is known

HttpWebResponse hanging up

try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
and
if(closeRequest == true) responseFile.Close();
So now my problem:
If i try to download a file, it does so, closes the response. All good.
However, if I type wrong URL (with 404 returned or smth), I can't close the response because it gives me nullreference error. So I close it only when I get a response.
However, after providing wrong URL and not closing response, further tries to download anything result in timeout (even if URL is correct).
Why is that happening and can I resolve it somehow?
EDIT: Full code of class:
public void DownloadAndReplace(string webFile, string sourceFile)
{
var requestFile = (HttpWebRequest)WebRequest.Create(webFile);
var requestMD5 = (HttpWebRequest)WebRequest.Create(webFile + ".md5");
var requestSHA = (HttpWebRequest)WebRequest.Create(webFile + ".sha");
bool closeRequest = true;
_location = sourceFile + "\\" + OriginalFileName(webFile);
requestFile.Method = "HEAD";
requestFile.Timeout = 2000;
HttpWebResponse responseFile = null;
HttpWebResponse responseMD5 = null;
HttpWebResponse responseSHA = null;
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
if (!File.Exists(_location) || responseFile.LastModified > File.GetLastWriteTime(_location))
{
downloadFile(webFile, _location);
if (_controlsRef.chooseMD5.Checked)
{
try
{
responseMD5 = (HttpWebResponse)requestMD5.GetResponse();
downloadFile(webFile + ".md5", _location);
responseMD5.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".md5");
}
}
else if (_controlsRef.chooseSHA1.Checked)
{
try
{
responseSHA = (HttpWebResponse)requestSHA.GetResponse();
downloadFile(webFile + ".sha", _location);
responseSHA.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".sha");
}
}
}
else MessageBox.Show("Newest version");
if(closeRequest == true) responseFile.Close();
public void downloadFile(string urlAddress, string location)
{
_fileHasher = new HashFile(_controlsRef);
using (var downloadClient = new WebClient())
{
downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = new Uri(urlAddress);
if (location == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
location = location + "\\" + OriginalFileName(urlAddress);
this._location = location;
}
else location = _location;
_downloadStopWatch.Start();
if (File.Exists(location))
{
File.Delete(location);
}
if (_isFile == true)
{
try
{
downloadClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_isFile = false;
}
}
}
}
private string OriginalFileName(string urlAddress)
{
var requestFile = (HttpWebRequest)WebRequest.Create(urlAddress);
requestFile.Method = "HEAD";
HttpWebResponse responseFile = null;
string originalFileName = "";
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exResponse)
{
MessageBox.Show(exResponse.Message);
_isFile = false;
}
if (_isFile == true)
{
int segmentLenght = responseFile.ResponseUri.Segments.Length;
originalFileName = responseFile.ResponseUri.Segments[segmentLenght - 1];
responseFile.Close();
}
return originalFileName;
}
To further clarify:
I provide URL for existing file 1. All is ok.
I provide URL for existing file 2. All is ok.
I provide URL for non-exisitng file 3. It throws me an 404 error.
I provide URL for existing file 4. I get program hangup and timeout.
Wrap your HttpWebResponse inside a using statement so that the object can be disposed correctly.
Something like this:
try
{
using(responseFile = (HttpWebResponse)requestFile.GetResponse())
{
...your code...
}
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
"using" reference: https://msdn.microsoft.com/en-us/library/yh598w02.aspx

530-5.5.1 Authentication required error, smtp

here is my FULL code below,Please need help, I have been trying to send email via gmail, I get this error "530-5.5.1 Authentication required", the exception occurs in the method called "Send()" on this line here: (see full code below), I am not using the c# library for some reason, so I need to get this to work, thanks.
//EXCEPTION OCCURS HERE, SEE THE SEND METHOD BELOW FOR FULL CODE
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
}
//CONSTRUCTOR
public Smtp()
{
Port =465 ;
Host = "smtp.gmail.com";
Email = "email#gmail.com";
Password = "xxxxxxx";
to = new List<String>() { "reciever#gmail.com"};
from = "sender#gmail.com";
}
//FULLE CODE
public void Connect()
{
if (Client == null)
Client = new TcpClient();
if (!Client.Connected)
Client.Connect(Host, Port);
//if (IsSecure)
//{
SslStream secureStream =
new SslStream(Client.GetStream());
secureStream.AuthenticateAsClient(Host);
ClientStream = secureStream;
secureStream = null;
Console.WriteLine("secure");
//}
//else
//{
// ClientStream = Client.GetStream();
// Console.WriteLine("non secure");
//}
Writer = new StreamWriter(ClientStream);
Reader = new StreamReader(ClientStream);
string c= ReadLine();
Console.WriteLine(c);
string message = "EHLO me";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
// throw new SmtpException(response);
}
Send();
}
// public void
public void Send()
{
string message = "MAIL FROM:<" + Email + ">";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
string x = ReadLine();
Console.WriteLine(x);
**//EXCEPTION OCCURS HERE**
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
catch (SmtpException e)
{
System.Console.WriteLine("{ 0}", e.Message);
}
}
message = "DATA\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "354")
{
throw new SmtpException(response);
}
message = "Subject: " + subject + "\r\n";
foreach (string address in to)
{
message += "To: " + address + "\r\n";
}
foreach (string address in cc)
{
message += "Cc: " + address + "\r\n";
}
message += "From: " + from + "\r\n";
if (bodyHtml.Length > 0)
{
message += "MIME-Version: 1.0\r\n"
+ " Content-Type: text/ html;\r\n"
+ " charset=\" iso-8859-1\"\r\n";
message += "\r\n" + bodyHtml;
}
else
{
message += "\r\n" + bodyText;
};
message += "\r\n.\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
message = "QUIT\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.IndexOf(" 221") == -1)
{
throw new SmtpException(response);
}
}
public void Close()
{
if (Client != null)
{
if (Client.Connected)
Logout();
Client.Close();
Client = null;
}
if (ClientStream != null)
{
ClientStream.Close();
ClientStream = null;
}
if (Writer != null)
{
Writer.Close();
Writer = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
disposed = true;
}
public void Dispose()
{
if (!disposed)
Close();
}
protected void Login()
{
if (!IsResponseOk(SendCommand("USER " + Email)) ||
!IsResponseOk(SendCommand("PASS " + Password)))
throw new Exception("User/password not accepted");
}
protected void Logout()
{
SendCommand("RSET");
//SendCommand("QUIT");
}
protected string SendCommand(string cmdtext)
{
Writer.WriteLine(cmdtext);
Writer.Flush();
return ReadLine();
}
protected string ReadLine()
{
return Reader.ReadLine() + "\r\n";
}
protected string ReadLines()
{
StringBuilder b = new StringBuilder();
while (true)
{
string temp = ReadLine();
if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
break;
b.Append(temp);
}
return b.ToString();
}
protected static bool IsResponseOk(string response)
{
if (response.StartsWith("+OK"))
return true;
if (response.StartsWith("-ERR"))
return false;
throw new Exception("Cannot understand server response: " +
response);
}
Clearly the SMTP server requires authentication before accepting mail to send. This is commonplace as spammers and scammers used to use 'open relays' to peddle their wares.
Check the rules for the server to see what authentication they will accept. The Wikipedia reference at http://en.wikipedia.org/wiki/SMTP_Authentication might be useful.

Categories

Resources