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);
Related
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.
I am trying to show an error message for failed recipients in my asp.net webpage. For some reason the code is not stepping into the SmtpFailedRecipientException:
SmtpClient client = new SmtpClient("smtp.server.com", 25) { Credentials = new NetworkCredential("any#one.com", "123456") };
using (var message = new MailMessage { })
{
message.From = new MailAddress(salesPersonDropDownList.SelectedItem.Text);
message.To.Add(mailToTextBox.Text);
message.CC.Add(mailToCCTextBox.Text);
message.CC.Add(mailToCCTextBox2.Text);
message.CC.Add(mailToCCTextBox3.Text);
message.Subject = mailSubjectTextBox.Text;
message.Body = mailBodyTextBox.Text;
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
string strSmtpFailedRecipientsException = "test";
}
catch (Exception ex)
{
string strException = "test";
}
}
The code is stepping properly into the the second "catch" but for some reason no into the SmtpFailedRecipientsException. Anyone can tell what I am doing wrong?
Thanks in advance
I found the problem by myself.
The SmtpFailedRecipientsException is for exceptions with two or more failed recipients - and in my case I always had only one failed recipient.
For one failed recipient I had to use the SmtpFailedRecipientException.
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 ).
Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}
After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);
Summary:
I need to login to my mailbox using EWS and but i keep getting 440/401 error.
question:
Anything obvious in my code as to why I keep getting either 401 or 440 errors?
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;
namespace MailboxListenerEWS
{
class Program
{
//Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C#
//can hardcode a username to connect a mailbox with
internal static string dUser = "username";//username to log into email account
internal static string dDomain = "domain";//domain of username used
internal static string dPassword = "Password";//password of username used
internal static string MailBoxAliasName = "mailboxname";//mailbox to authenticate too
internal static string ExchangeServerName = "exchangeName"; //not always needed
internal static string ReadAttachments = "0"; //1 means read attachments, 0 means dont
internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from
static void Main(string[] args)
{
//Connect to server
//ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
//service.Credentials = new NetworkCredential("name", "pwd", "domain");
service.Credentials = new NetworkCredential("dUser", "dPassword", "dDomain");
//log in to mailbox
try
{
//service.Url = new Uri(serviceurl);
//Console.WriteLine(serviceurl);
//service.AutodiscoverUrl(MailBoxAliasName);
service.Url = new Uri("https://" + ExchangeServerName + "/EWS/" + MailBoxAliasName + "/inbox");
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
Console.ReadLine();
}
//List folders
try
{
//Listing all the subfolders of the Inbox
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
foreach (Item item in findResults)
{
Console.WriteLine(item.Subject);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: " + ex.Message);
Console.ReadLine();
}
}
}
}
Are you sure your server uses 2007 SP1? Also, if you're not sure of the correct URL, try using the AutoDiscover, where "user#domain.com" is an actual email address on your domain.
service.AutodiscoverUrl("user#domain.com");
Also, you're setting your URL equal to a URi . I don't think that's legal; is it even compiling?
Here is some sample code that I used as a starting point when I implemented something similar - codeproject.com