SMTP Email Error - visual-studio-2010

I am using Visual Studio 2010. I am trying to send an email to 1 email address when the user hits submit. I am getting the error below:
Error: Syntax error, command unrecognized. The server response was: 5.0.0 Your email system must authenticate before sending mail:
Here is my code in my code behind:
public void SendMail(string FromEmail, string ToEmail, string Subject, string Body)
{
System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
eMail.From = new System.Net.Mail.MailAddress(FromEmail);
//MailMessage eMail = new MailMessage();
//eMail.From = new MailAddress(FromEmail);
eMail.To.Add(ToEmail);
eMail.Subject = Subject;
eMail.IsBodyHtml = true;
eMail.Body = Body;
SmtpClient SMTP = new SmtpClient();
//SMTP.Host = "mail.authsmtp.com";
//SMTP.UseDefaultCredentials = true;
//SMTP.EnableSsl = true;
SMTP.Send(eMail);
eMail.Dispose();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
StringBuilder sbBody = new StringBuilder();
string FromEmail = "smit#college.edu";
string ToEmail = "smit#college.edu";
string Subject = "Application for" + " " + txtFirstName.Text + " " + txtLastName.Text + " " + "created on:" + " " + txtDateCreated.Text;
sbBody.Append("Click link below to view application for" + " " + txtFirstName.Text + " " + txtLastName.Text);
sbBody.Append("<br/>");
sbBody.Append("<br/>");
sbBody.Append("AdminDisplay.aspx?ID=#ID");
sbBody.Append("<br/>");
sbBody.Append("Thank you,");
sbBody.Append("Admin");
SendMail(FromEmail, ToEmail, Subject, sbBody.ToString());
}
Here is my web.config:
<system.net>
<mailSettings>
<smtp from="smit#college.edu">
<network host="mail.authsmtp.com" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
I have been working on this most of the day and need to get it working. Thank you

Related

Send a mail that has Arabic characters using Gmail API

I am trying to send a mail using google.Apis.Gmail.v1 and MimeKit, but the issue is that when I use Arabic characters, the receiver receives gibberish text.
My code is below:
var mail = new MimeMessage();
mail.From.Add(new MailboxAddress("From Name", "DoNotReply#someDomain.com"));
mail.To.Add(new MailboxAddress("To Name","customerAddress#someDomain.com"));
mail.Subject = "كشف حساب من تاريخ " + dateTimePicker1.Text + " حتى تاريخ " + dateTimePicker2.Text;
var text_part = new TextPart(MimeKit.Text.TextFormat.Plain);
string body = #"<table border='1'><table style='background-color:#E5E4E2;'><tr><tr style='background-color:#1e90ff;color:#ffffff;'><td>تراكمي</td><td>دائن</td><td>مدين</td><td>البيان</td><td>المرجع</td><td>التاريخ</td></tr>";
foreach (ListViewItem lstitem in listView1.Items)
{
body += #"<tr><td>" + lstitem.SubItems[1].Text + "</td><td>" + lstitem.SubItems[2].Text + "</td><td>" + lstitem.SubItems[3].Text + "</td><td>" + lstitem.SubItems[4].Text + "</td><td>" + lstitem.SubItems[5].Text + "</td><td>" + lstitem.SubItems[6].Text + "</td></tr>";
}
body += #"</table></style></style>";
body += #"<br /><br /> المبلغ المطلوب " + sum1s.Text;
body += #"<br /><br /> Thank You";
mail.Body = new TextPart("html") { Text = body };
byte[] bytes = Encoding.UTF8.GetBytes(mail.ToString());
string raw_message = Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
UserCredential credential;
//read your credentials file
using (FileStream stream = new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Program.Scopes, "user", CancellationToken.None, new FileDataStore(path, true)).Result;
}
//call your gmail service
var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Program.ApplicationName });
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = raw_message;
service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("تم ارسال التقرير بنجاح", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
And what I receive is:
تراكمي دائن مدين البيان المرجع التاريخ
985.00 58228.00 57243.00 رصيد منقول - 01/03/2022 00:00:00 AM
985 58228 -57243 المجموع الكلي - 11/03/2022 09:49:42 AM
المبلغ المطلوب + 985 شيكل
Thank You

Email body returns a blank or null in chilkat mail

I have the following code that reads a bunch of emails from a folder. It gets the emails fine, as I can see the number of emails are correct and the header is correct as well.
However it returns nothing for the body. I do have a email with simple text as well but that too does not return anything. Part of the code is below.
any help is appreciated. the account I am reading is from a office 365 and i used the imap.Connect
(*i can read these emails from the Microsoft Outlook, so i think the issue is with my chilkat code)
Chilkat.MessageSet messageSet = imap.Search(#"ALL", fetchUids);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Fetch the email headers into a bundle object:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Sort the email bundle by date, recipient, sender, or subject:
bool ascending = true ; bool descending = true;
bundle.SortByDate(ascending);
//bundle.SortByDate(descending);
// To sort by recipient, sender, or subject, call
// SortBySender, SortByRecipient, or SortBySubject.
// Display the Subject and From of each email.
int i = 0;
string body="";
while (i < bundle.MessageCount)
{
Chilkat.Email email = null;
email = bundle.GetEmail(i);
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + email.GetHeaderField("Date");
//Debug.WriteLine(email.GetHeaderField("Date"));
//Debug.WriteLine(email.Subject);
txtOutput.Text = txtOutput.Text + Environment.NewLine + email.From;
//Debug.WriteLine(email.From);
//Debug.WriteLine("--");
if (email.HasHtmlBody())
{
body = email.GetHtmlBody() + String.Empty;
}
else if (email.HasPlainTextBody())
{
body = email.GetPlainTextBody() + String.Empty;
}
else
{
body = email.Body + String.Empty;
}
txtOutput.Text = txtOutput.Text + Environment.NewLine + body.Trim() ;
i = i + 1;
}
You downloaded headers-only:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
Of course there is no body...

xxxxxx is not a valid path. Make sure that the path name is

I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}

whats failed due to data type mismatch in criteria expression c#?

am trying to develop a c# standalone application and my insert code has no error but when i click it will insert to first table or crtPro perfectly but it didn't add to the second table , can anyone give me some hint...???
here is my code for insert code...
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Documents and Settings\abel\My Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Address = txtAddress.Text.ToString();
//String Wereda = txtWereda.Text.ToString();
//String Kebele = txtKebele.Text.ToString();
//String House_No = txtHouse.Text.ToString();
//String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
//String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String Status = ToString();
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "INSERT INTO crtPro(Name,Address,Email,Tel,Item,Dep,Status,Remark)VALUES('" + Name + "','" + Address + "','" + Email + "','" + Tel + "','" + Item + "','" + Dep + "','" + Remark + "')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
String my_querry1 = "SELECT LAST(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
//txtStatus.Text = var;
String PID = ToString();
String my_querry2 = "INSERT INTO crtItemLicense(PID,Type,Brand,License_No,Date_issued)VALUES('" +PID + "','" + Type + "','" + Brand + "','" + License_No + "','" + Date_issued + "')";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
There are a couple of calls like:
String PID = ToString();
That will try to get a string representation of 'this', which is your form. That is probably not what you want to be inserting into the database. You probably meant
String PID = var.ToString();
If that isn't it, then try putting more tracewrites (or using a debugger) to narrow the problem down to find which one of your sql statements is causing the problem.
Also once you have it working, try entering this in the name field of your form:
Robert"); DROP TABLE crtPro;--
and then do some googling about SQL injection (apologies to XKCD).

How can I get the Exchange Server programmatically from my App(C#)

Currently I can send email successfully through WebDAV with C#, but there is a shortage in my App that I have hard-code the Exchange Server of my outlook, so it might only works for me, if it were moved to another PC and use another outlook account, it might not work because the Exchange Server for this outlook account might not the same as mine(that's beacuse our company for different email account might assign different Exchange server), so my question is that how can I get the Exchange Server for the current Email accout dynamically. In fact I can get this Exchange Server from the outlook client when I clicked the menu item to add a new Outlook Account, but dose there exist any API for me to get this Exchange Server programmatically such as with C#?
In fact I use the following code to send Email:
using System;
using System.Net;
using System.IO;
namespace WebDavNET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
try
{
// TODO: Replace with the name of the computer that is running Exchange 2000.
string strServer = "ExchServe";
// TODO: Replace with the sender's alias.
string strSenderAlias = "sender";
// TODO: Replace with the sender's e-mail address.
string strFrom = "sender#example.com";
// TODO: Replace with the recipient's e-mail address.
string strTo = "recipient#example.com";
string strSubject = "Send Using HttpWebRequest";
string strBody = "Hello World";
string sUri;
sUri = "http://" + strServer + "/Exchange/" + strSenderAlias;
sUri = sUri + "/%23%23DavMailSubmissionURI%23%23/";
System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
DateTime mySentTime = new DateTime();
sQuery = "From: " + strFrom + "\n" +
"To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + DateTime.Now.ToString() + "\n" +
"X-Mailer: My DAV mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" + "\n" +
strBody;
// Set the credentials.
// TODO: Replace with the appropriate user credential.
NetworkCredential myCred = new NetworkCredential(#"DomainName\User", "Password");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set the headers.
HttpWRequest.Headers.Set("Translate", "f");
HttpWRequest.ContentType = "message/rfc822";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes.
HttpWRequest.Timeout = 300000;
// Set the request method.
HttpWRequest.Method = "PUT";
// Store the data in a byte array.
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send the request and get the response.
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code.
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers.
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the response stream.
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close the stream.
strm.Close();
// Clean up.
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}
As you can see in the code there is a variable named "strServer", In my App I just hard-code my Exchange Server for this variable, so my question is that dose there exist any API for me to get the Exchange Server dynamically for the specific outlook account?
Thanks!
You can use EWS(exchange Web Services) too. here is the link
You can use XML creator for creating items or requests required for operations in the link. Just go through the operations given on the link.

Resources