I am facing an issue while reading emails from my exchange email account using EWS Microsoft API.
Please help me with a solution if anybody has.
Used below code
public static void Main(string[] args)
{
string UserName = "**";
string Password = "**";
string EXCHANGEMAILURL = # "<Exchange Webservice URL>";
ExchangeService service = new ExchangeService();
service.Timeout = 500000;
service.Credentials = new NetworkCredential(UserName, Password);
service.Url = new Uri(EXCHANGEMAILURL);
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
FindFoldersResults folderSearchResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(int.MaxValue));
Folder xChangeSourceFolder = folderSearchResults.Folders.ToList().Find(
f => f.DisplayName.Equals("Inbox", StringComparison.CurrentCultureIgnoreCase));
ItemView itemView = new ItemView(50);
FindItemsResults<Item> findIncomingMails = service.FindItems(xChangeSourceFolder.Id, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
new ItemView(50));
Item item = findIncomingMails.First();
EmailMessage messageHTML = (EmailMessage) item;
messageHTML.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments, ItemSchema.Body) {
RequestedBodyType = BodyType.HTML
});
string htmlString = messageHTML.Body.Text.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred: " + ex);
}
}
The exception
Unable to connect to the remote server :
A connection attempt failed because the connected party did not properly respond after a period of time,or established connection failed because connected host has failed to respond.
It was working before, but since last 1-2 weeks, it stopped working.
Related
i keep getting authentication failed error after i provide proxy information to Pop3Client. Connection is fine but authentication part gives the following error:
ProxySettings ProxySetting = new ProxySettings
{
Name = "asaf",
Host = "192.168.3.55",
Port = 808,
Auth = new Authorization
{
Type = AuthenticationMethodConstants.Ntlm,
User = "User-001",
Password = "Deneme123"
}
};
using (var client = new Pop3Client())
{
client.Timeout = 120000;
if (ProxySetting != null)
{
client.ProxyClient = ProxySetting.CreateHttpProxyClient();
Console.WriteLine("Current proxy: " + client.ProxyClient.ProxyHost + ":" + client.ProxyClient.ProxyPort);
}
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("outlook.office365.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate("mcs234#lenfs.onmicrosoft.com", "phtfg456!");
Interesting thing is that I just tried the same code with ImapClient with port 993 and it worked just fine. It seems problem is only for Pop3 protocol.
I have windows service that working every 10 second. It's working fine generally but sometimes im getting these errors;
at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.Execute()
at OutlookService.ItemLoad(EmailMessage message, List1& attachmentList) in \OutlookService.cs:line 69; The request failed. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
25.09.2019 15:03:53: Microsoft.Exchange.WebServices:at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(IEwsHttpWebResponse response)
My problem is if that mail got error while reading it cannot be read again. Its stay unread mail but i cannot get it.
My Code;
private static ExchangeService Service2013
{
get
{
if (_service2013 == null)
{
var uname = "mail";
var pwd = "pass";
_service2013 = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
_service2013.Credentials = new WebCredentials(uname, pwd);
_service2013.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
}
return _service2013;
}
}
ExchangeService service = OutlookService.Service;
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
try
{
FindItemsResults<Item> findResults;
ItemView view = new ItemView(100);
do
{
findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
if (findResults.Items.Count > 0)
{
foreach (var item in findResults.Items)
{
item.Load();
var emailMessage = item as EmailMessage;
if (!string.IsNullOrEmpty(emailMessage.Subject))
{
if (!emailMessage.Subject.ToLower().Contains("automatic reply") && !emailMessage.Subject.ToLower().Contains("otomatik yanıt"))
{
ReadMail(item as EmailMessage);
GC.SuppressFinalize(item);
}
else
{
emailMessage.IsRead = true;
emailMessage.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
else
{
ReadMail(item as EmailMessage);
GC.SuppressFinalize(item);
}
}
}
view.Offset = findResults.NextPageOffset.GetValueOrDefault(0);
GC.SuppressFinalize(findResults);
} while (findResults.MoreAvailable);
GC.SuppressFinalize(view);
}
catch (Exception ex)
{
//Debug.WriteLine(string.Format("Operate Error {0}.", ex.Message));
Logger.WriteLog(ex);
}
I am trying to send Email from my company mail , when i use this code
i got
public String SendMail(String Email)
{
try
{
var client = new SmtpClient("smtp.gmail.com",587)
{
Credentials = new System.Net.NetworkCredential("************#itsans.com", "*********"),
EnableSsl = true
};
// client.UseDefaultCredentials = false;
String VerCode = CreateRandomCode(4);
AppUserBusiness appuser = new AppUserBusiness();
String InsertVer = appuser.ForgotPassword(Email, VerCode);
if (InsertVer == "Done")
client.Send("*********#itsans.com", Email, "iBlink Verification", "Your Verification Code is :" + VerCode);
return InsertVer;
}
catch (Exception Ex)
{
Logging.WriteToFile(Ex.Message, Ex.StackTrace);
return "Fail";
}
}
{"Unable to connect to the remote server"}
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 72.167.238.29:587"}
I am trying to send e-mail from within a Xamarin Forms app, using Gmail.
I have created an Interface with only 1 method: SendEmail();
Then, in the Droid project, I added a class which implements said interface. Using the Dependency attribute and getting the implementation of the method in the main project, all is fine, except the following error:
Could not resolve host 'smtp.gmail.com'
This is the actual implementation of the method:
string subject = "subject here ";
string body= "body here ";
try
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("myEmailAddress#gmail.com");
mail.To.Add("anotherAddress#yahoo.com");
mail.Subject = subject;
mail.Body = body;
smtpServer.Credentials = new NetworkCredential("username", "pass");
smtpServer.UseDefaultCredentials = false;
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
Searching around I could not find any details regarding it other that the actual smtp address.
Also, I have used the Less Secure apps procedure from Google, not receiving a credentials error I assume that it can connect to the account just fine.
Hello I have achieve this using the code below, also I have attached a file to the email, using the dependency service I use this methods:
Android:
public static string ICSPath
{
get
{
var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
Intent choserIntent = new Intent(Intent.ActionSend);
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
Java.IO.File filelocation = new Java.IO.File(ICSPath);
var path = Android.Net.Uri.FromFile(filelocation);
// set the type to 'email'
choserIntent.SetType("vnd.android.cursor.dir/email");
//String to[] = { "asd#gmail.com" };
//emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
choserIntent.PutExtra(Intent.ExtraStream, path);
// the mail subject
choserIntent.PutExtra(Intent.ExtraSubject, "Calendar event");
Forms.Context.StartActivity(Intent.CreateChooser(choserIntent, "Send Email"));
return true;
}
iOS:
public static string ICSPath
{
get
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
MFMailComposeViewController mail;
if (MFMailComposeViewController.CanSendMail)
{
mail = new MFMailComposeViewController();
mail.SetSubject("Calendar Event");
//mail.SetMessageBody("this is a test", false);
NSData t_dat = NSData.FromFile(ICSPath);
string t_fname = Path.GetFileName(ICSPath);
mail.AddAttachmentData(t_dat, #"text/v-calendar", t_fname);
mail.Finished += (object s, MFComposeResultEventArgs args) =>
{
//Handle action once the email has been sent.
args.Controller.DismissViewController(true, null);
};
Device.BeginInvokeOnMainThread(() =>
{
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mail, true, null);
});
}
else
{
//Handle not being able to send email
await App.BasePageReference.DisplayAlert("Mail not supported",
StaticData.ServiceUnavailble, StaticData.OK);
}
return true;
}
I hope this helps.
Figured it own finally!
First of all, I was using Android Player by Xamarin, which apparently does not support network connectivity.
So my fix was easy: used an Android Emulator ( any version of it for that matter ) built in Visual Studio Community 2015, and tested network connectivity using the plugin by James Montemagno ( Xam.Plugin.Connectivity on NuGet ).
I want to access exchange server by using .NET 3.5. Here is my code:
class Program
{
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials("email_test#xxx.com", "abcd");
service.AutodiscoverUrl("email_test#xxx.com");
EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("abc#xxx.com");
message.SendAndSaveCopy();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
I am referring this article to write the codes:
But I receive this exception:
AutodiscoverLocalException: The Autodiscover service couldn't be located.
Anyone can help?
I had this issue and it was due the user account being locked out.
service.Credentials = new WebCredentials("<loginID..not email address>", "< the pw>");
service.AutodiscoverUrl("<your emailaddress>",RedirectionUrlValidationCallback);