Check if Email Address Belongs to Yahoo? - asp.net

private byte[] BytesFromString(string str)
{
return Encoding.ASCII.GetBytes(str);
}
private int GetResponseCode(string ResponseString)
{
return int.Parse(ResponseString.Substring(0, 3));
}
protected void Button1_Click(object sender, EventArgs e)
{
TcpClient tClient = new TcpClient("plus.smtp.mail.yahoo.com", 465);
string CRLF = "\r\n";
byte[] dataBuffer;
string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("HELO " + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("MAIL FROM:<myemail#yahoo.com>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("RCPT TO:<" + TextBox1.Text.Trim() + ">" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
if (GetResponseCode(ResponseString) == 550)
{
Response.Write("Mai Address Does not Exist !");
}
dataBuffer = BytesFromString("QUITE" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
tClient.Close();
}
Hi, this code does not work with smtp yahoo server but code work with gmail smtp server TcpClient tClient = new TcpClient("gmail-smtp-in.l.google.com", 25)
error:An established connection was aborted by the software in your host machine in line Response String = reader.ReadLine();
and change port server to 25 not happen!
Whether smtp server and port server is valid?
Is there a way to make sure of is email valid?
someone could help me?

Some Server machine used to algorithm for responsing to fetch data from it's particular server than that machine can't responding.....
but as you say gmail provide data therefore that machine can't use any restriction for responding data......

Related

Tableau Unexpired Trusted Ticket - including ClientIP

I have an ASP.NET web application in which I'm rendering different tableau dashboards from a site based on the menu clicked by the user. I have multiple menus and each menu was tied to a tableau URL.
Tableau Trusted Authentication has been implemented to get the trusted ticket from the tableau server. Once the ticket has been retrieved, I am appending the ticket to the dashboard URL along with the server name for each menu.
The trusted ticketing module is working fine and the visualizations are getting rendered in my web application. However, frequently I am getting a message of "Could not locate unexpired ticket" error.
On checking with this error, this is due to the ticket calls getting duplicated.
I reached out to the support regarding this and got a response that I can add client_ip during my trusted ticketing.
Tableau Trusted Ticket
I am not able to find any code article related to adding client_ip in trusted ticketing.
Below is my trusted ticket code.
public class TableauTicket
{
public string getTableauTicket(string tabserver, string sUsername)
{
try
{
ASCIIEncoding enc = new ASCIIEncoding();
string postData = string.Empty;
string resString = string.Empty;
postData = "username=" + sUsername + "";
// FEATURE 816 END - Custom Visualization - KV
if (postData != string.Empty)
{
byte[] data = enc.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
req.ContentLength = data.Length;
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(stream: res.GetResponseStream(), encoding: enc);
resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
else
{
resString = "User not authorised";
return resString;
}
}
catch (Exception ex)
{
string resString = "User not authorised";
return resString;
string strTrailDesc = "Exception in tableau ticket - " + ex.Message;
}
}
public int Double(int i)
{
return i * 2;
}
}
Can anyone please let me know how the client_ip can be passed in trusted ticketing code?
Also, the client IP will get changed for each user and how this will be handled in the trusted ticketing?
UPDATE
I have solved the issue using the source code provided by tableau on how to embed the view in SharePoint.
Below is the code which may help users having the same issue.
string GetTableauTicket(string tabserver, string tabuser, ref string errMsg)
{
ASCIIEncoding enc = new ASCIIEncoding();
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
string postData = "username=" + tabuser + "&client_ip=" + Page.Request.UserHostAddress;
byte[] data = enc.GetBytes(postData);
try
{
string http = _tabssl ? "https://" : "http://";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(http + tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// Write the request
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
// Do the request to get the response
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(res.GetResponseStream(), enc);
string resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
// if anything bad happens, copy the error string out and return a "-1" to indicate failure
catch (Exception ex)
{
errMsg = ex.ToString();
return "-1";
}
}
Assuming your code is working, (I have done this part in Java and not really an expert in asp.net) all you have to do is to add something like:
postData = postData +"&client_ip=" +<variable for client IP>;
The way it is handled on tableau server is :
you turn on wgserver.extended_trusted_ip_checking on Tableau server. see details here
Tableau will match the client IP you passed in the POST request 'client_ip=XXX.XXX.XXX.XXX' while obtaining the token, with the actual IP of the the machine where the browser is trying to access tableau server.

Sending multiple mail using aync in asp.net

I have to send mail to multiple recipient eg. to all the employee of an organization. For this I go through the resources via search engine and decided to make multiple instant of SmtpClient and send mail using async. So for test I write following code having gmail test server.
public void SendMail()
{
try
{
string strEmail = string.Empty;
// for collecting multiple recepient
//foreach (GridViewRow grd in gdv_txtMailTo.Rows)
//{
// CheckBox chkBx = (CheckBox)grd.FindControl("chkBxSelect");
// if (chkBx != null && chkBx.Checked)
// {
// strEmail += ((Label)grd.FindControl("Label1")).Text + ',';
// }
//}
strEmail = "yogendra.paudyal44#gmail.com";
string emails = strEmail;
string output = DBNull.Value.ToString();
//if (emails != "")
//{
// output = emails.Remove(emails.Length - 1, 1);
//}
MassMail_Controller.SaveSelectedEmails(output, PortalID);
MassMail_Info info = new MassMail_Info();
info.SendFrom = txtMailFrom.Text;
info.Subject = txtSubject.Text;
info.CC = txtCC.Text;
info.BCC = txtBCC.Text;
info.FileName = "";
info.SendTo = strEmail;
string messageTemplate = txtBody.Text;
info.Body = messageTemplate;
info.UserModuleId = UserModuleID;
info.PortalId = PortalID;
for (int i = 0; i < 50; i++) {
MailHelper.SendMailOneAttachment(info.SendFrom, info.SendTo, info.Subject, info.Body, info.FileName, info.CC, info.BCC);
}
//Thread thread = new Thread(new ParameterizedThreadStart(GetAllEmail));
//thread.IsBackground = true;
//thread.Start(bit);
//while (thread.IsAlive)
//{
// ShowMessage(SageMessageTitle.Exception.ToString(), "Mail Sent", "", SageMessageType.Success);
//}
}
catch (Exception ex)
{
ProcessException(ex);
}
}
And mailHelper would be:
public static void SendEMail(string From, string sendTo, string Subject, string Body, ArrayList AttachmentFiles, string CC, string BCC, bool IsHtmlFormat)
{
SageFrameConfig sfConfig = new SageFrameConfig();
//string ServerPort = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPServer);
//string SMTPAuthentication = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPAuthentication);
//string SMTPEnableSSL = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPEnableSSL);
//string SMTPPassword = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPPassword);
//string SMTPUsername = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPUsername);
string ServerPort = (SageFrameSettingKeys.SMTPServer);
string SMTPAuthentication =(SageFrameSettingKeys.SMTPAuthentication);
string SMTPEnableSSL = (SageFrameSettingKeys.SMTPEnableSSL);
string SMTPPassword = (SageFrameSettingKeys.SMTPPassword);
string SMTPUsername = (SageFrameSettingKeys.SMTPUsername);
string[] SMTPServer = ServerPort.Split(':');
try
{
MailMessage myMessage = new MailMessage();
myMessage.To.Add(sendTo);
myMessage.From = new MailAddress(From);
myMessage.Subject = Subject;
myMessage.Body = Body;
myMessage.IsBodyHtml = true;
if (CC.Length != 0)
myMessage.CC.Add(CC);
if (BCC.Length != 0)
myMessage.Bcc.Add(BCC);
if (AttachmentFiles != null)
{
foreach (string x in AttachmentFiles)
{
if (File.Exists(x)) myMessage.Attachments.Add(new Attachment(x));
}
}
SmtpClient smtp = new SmtpClient();
if (SMTPAuthentication == "1")
{
if (SMTPUsername.Length > 0 && SMTPPassword.Length > 0)
{
smtp.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
}
}
smtp.EnableSsl = bool.Parse(SMTPEnableSSL.ToString());
if (SMTPServer.Length > 0)
{
if (SMTPServer[0].Length != 0)
{
smtp.Host = SMTPServer[0];
if (SMTPServer.Length == 2)
{
smtp.Port = int.Parse(SMTPServer[1]);
}
else
{
smtp.Port = 25;
}
object userState = myMessage;
//wire up the event for when the Async send is completed
smtp.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
smtp.SendAsync(myMessage,userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
//string answer = Console.ReadLine();
// If the user canceled the send, and mail hasn't been sent yet,
// then cancel the pending operation.
//if (answer.StartsWith("c"))
//{
// smtp.SendAsyncCancel();
//}
//// Clean up.
//myMessage.Dispose();
Console.WriteLine("Goodbye.");
}
else
{
throw new Exception("SMTP Host must be provided");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
This code snippet works fine but I couldnot send specified number of mail. The number of email sent is differnt each time I execute this code ie. it may be 35, 40, 42 etc. It seems some instances of SmtpClient got failed, but I didnot get any exception. Am I doing something wrong. Do We have better option to send multiple mail at one time?
I want to share my experience with sending emails.I also used to send B-Day emails but in my case there were usually 100-150 people and all mails delivered successfully. I had made a web service for this whose only task was to send emails. But before emails started to deliver successfully we tested on local machine which worked fine but when we tested it on server i face the same issue and cause of this failure was that we deployed our web service in .Net framework 2.0 than we changed it to 4.0 and tested it again with 10000,5000,1000 emails and it worked fine not all emails but most of them reached destination.Also one more thing to mention is that the address from which we were sending email was restricted by network department in email server to send only 100 emails.Also try to avoid sending too many emails from one sender and from one email server because you can get black listed.
Summary
First of all check that are you using .Net framework 2.0 if yes
switch to 4.0.
Make sure that there are no restrictions by network department at
email server and also to address which you use as sender.
Place all your code in using statement to make sure objects get
disposed.
Send your emails in chunks(About 100 at a time).
using()
{
//Place you email sending code here.
}

Sending Push SMS from an Asp.net Application

PLease let me know a method on, How I can send a Push SMS to mobile numbers from asp.net application. Thanks in Advance.
Try out this code,
protected void Page_Load(object sender, EventArgs e)
{
textboxRecipient.Width = 400;
textboxMessage.Width = 450;
textboxMessage.Rows = 10;
textboxError.Width = 400;
textboxError.Rows = 5;
textboxError.ForeColor = System.Drawing.Color.Red;
textboxError.Visible = false;
textboxError.Text = "";
if (!Page.IsPostBack)
{
textboxRecipient.Text = "+7588451632";
textboxMessage.Text = "Hello World!";
}
}
protected void buttonSendOnClick(object sender, EventArgs e)
{
//are required fields filled in:
if (textboxRecipient.Text == "")
{
textboxError.Text += "Recipient(s) field must not be empty!\n";
textboxError.Visible = true;
return;
}
//we creating the necessary URL string:
string ozSURL = "http://127.0.0.1"; //where Ozeki NG SMS Gateway is running
string ozSPort = "9501"; //port number where Ozeki NG SMS Gateway is listening
string ozUser = HttpUtility.UrlEncode("admin"); //username for successful login
string ozPassw = HttpUtility.UrlEncode("abc123"); //user's password
string ozMessageType = "SMS:TEXT"; //type of message
string ozRecipients = HttpUtility.UrlEncode(textboxRecipient.Text); //who will get the message
string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of message
string createdURL = ozSURL + ":" + ozSPort + "/httpapi" +
"?action=sendMessage" +
"&username=" + ozUser +
"&password=" + ozPassw +
"&messageType=" + ozMessageType +
"&recipient=" + ozRecipients +
"&messageData=" + ozMessageData;
try
{
//Create the request and send data to Ozeki NG SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL);
//Get response from Ozeki NG SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
//inform the user
textboxError.Text = responseString;
textboxError.Visible = true;
}
catch (Exception)
{
//if sending request or getting response is not successful Ozeki NG SMS Gateway Server may do not run
textboxError.Text = "Ozeki NG SMS Gateway Server is not running!";
textboxError.Visible = true;
}
}

Send mail using SMTP server

Hell Guys!
I have used SMTP server to send mail as per below
public bool SendMail(string mailFrom, string mailTo, string mailCC, string mailBCC, string subject, string body, string attachment, bool isBodyHtml)
{
bool SendStatus = false;
System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage(mailFrom, mailTo);
if (mailCC != string.Empty)
mailMesg.CC.Add(mailCC);
if (mailBCC != string.Empty)
mailMesg.Bcc.Add(mailBCC);
if (!string.IsNullOrEmpty(attachment))
{
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(attachment);
mailMesg.Attachments.Add(attach);
}
mailMesg.Subject = subject;
mailMesg.Body = body;
mailMesg.IsBodyHtml = isBodyHtml;
mailMesg.ReplyTo = new System.Net.Mail.MailAddress(mailFrom);
System.Net.Mail.SmtpClient objSMTP = new System.Net.Mail.SmtpClient();
string Host = System.Configuration.ConfigurationManager.AppSettings["MailHost"].ToString();
string UserName = System.Configuration.ConfigurationManager.AppSettings["MailUserId"].ToString();
string password = System.Configuration.ConfigurationManager.AppSettings["MailPassword"].ToString();
objSMTP.Host = Host;
objSMTP.Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"].ToString());
objSMTP.Credentials = new System.Net.NetworkCredential(UserName, password);
objSMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
try
{
objSMTP.Send(mailMesg);
SendStatus = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
mailMesg.Dispose();
mailMesg = null;
}
return SendStatus;
}
I would like to know that Is it possible to send mail without username & password ?
If possible then can anyone please suggest me how to do that?
Sure, if your smtp server doesn't require cridentials you shouldn't specify em. Otherwise you should.
I think you need to white list the ip that you will send e-mail from which will be your server and this option is done on the mail account that you are going to send e-mails from.

Downloading file via TcpClient from HTTP server

I`m learning HTTP, and decide to use TcpClient for downloading file from internet.
private void requireBtn_Click(object sender, EventArgs e) {
var client = new TcpClient(addressBox.Text, 80);
var networkStream = client.GetStream();
var sWriter = new StreamWriter(networkStream, Encoding.Default);
foreach (string querLine in queryBox.Lines) {
sWriter.WriteLine(querLine);
}
sWriter.WriteLine();
sWriter.Flush();
string responceText = "";
var sReader = new StreamReader(networkStream);
string respLine;
while ((respLine = sReader.ReadLine()).Length > 0) {
responceText += respLine + "\r\n";
}
responceBox.Text = responceText;
Regex reContentLength = new Regex(#"(?<=Content-Length:\s)\d+", RegexOptions.IgnoreCase);
Int32 contentLength = Int32.Parse(reContentLength.Match(responceText).Value);
this.Text = contentLength.ToString();
if (networkStream.CanRead) {
var fileStream = new FileStream(#"C:\img.png", FileMode.Create);
byte[] buffer = new byte[1024];
int numberOfBytesRead = 0;
do {
numberOfBytesRead = networkStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, numberOfBytesRead);
}
while (networkStream.DataAvailable);
fileStream.Flush();
fileStream.Close();
MessageBox.Show("Done!");
}
else
MessageBox.Show("Fail!");
client.Close();
}
But downloaded file is corrupted. I can't understand why...
Source file
private void requireBtn_Click(object sender, EventArgs e) {
string host = "atomAltera.SkyHost.ge";
string query = "GET /mems.txt HTTP/1.1\r\n" +
"Host: atomAltera.SkyHost.ge\r\n" +
"User-Agent: NuclightWeb\r\n" +
"Connection: close\r\n"+
"\r\n";
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
client.Connect(host, 80);
var networkStream = new NetworkStream(client);
var bytes = Encoding.Default.GetBytes(query);
networkStream.Write(bytes, 0, bytes.Length);
var bReader = new BinaryReader(networkStream, Encoding.Default);
string responce = "";
string line;
char c;
do {
line = "";
c = '\u0000';
while (true) {
c = bReader.ReadChar();
if (c == '\r')
break;
line += c;
}
c = bReader.ReadChar();
responce += line + "\r\n";
} while (line.Length > 0);
responceBox.Text = responce;
Regex reContentLength = new Regex(#"(?<=Content-Length:\s)\d+", RegexOptions.IgnoreCase);
Int32 contentLength = Int32.Parse(reContentLength.Match(responce).Value);
this.Text = contentLength.ToString();
var fileStream = new FileStream(#"C:\m.txt", FileMode.Create);
byte[] buffer = new byte[4 * 1024];
int n = 0;
int read = 0;
while (n < contentLength) {
if (networkStream.DataAvailable) {
read = networkStream.Read(buffer, 0, buffer.Length);
n += read;
fileStream.Write(buffer, 0, read);
}
}
fileStream.Flush();
fileStream.Close();
client.Close();
}
It Works! May be StreamReader reads superfluous bytes?
I suggest using contentLength instead of networkStream.DataAvailable to detect when the data transfer is complete.
DataAvailable simply means that there is data received by the OS stack, however depending on the network routing and fragmentation it might not have arrived by the time you're checking the condition, so you stop receiving that data too early.
To prove or disprove this, you can do a binary file comparison between what your program has downloaded versus what a normal browser would download. If the former is truncated, then we've found the problem.
You need to use the value from the Content-Length header (which can be larger than a 32-bit integer, btw). Keep reading until that many bytes have been received.
However, it is possible for the server to not use a Content-Length header at all. It may use a Transfer-Encoding header that includes the chunked coding, or it may not use any header at all. HTTP defines several different ways to determine the length of the data, and you should support as many as you can in order to account for all kinds of servers. See RFC 2616 Sections 4.3 and 4.4 for the particular rules you need to follow.

Resources