I am working on EMAIL service and trying to get emails using IMAP Ae.net.mail, I am able to read the emails from GMAIL comfortably but when i try to do it for Outlook express it throws an exception as given below
Error :
xm007 bad command argument 11
The code is given below for authentication which work fine
ImapClient ic = new ImapClient("outlook.office365.com", MailBoxID, Password,
AuthMethods.Login, 993), true);
IMAPService im = new IMAPService();
im.LoadExchangeEmail(ic, dtEmailServer.Rows[i]);
Now, when i am trying to read email it gives me an exception as i mentioned above
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using AE.Net.Mail;
using AE.Net.Mail.Imap;
using EmailDownloadService.Library;
namespace EmailDownloadService
{
public class IMAPService
{
public void LoadExchangeEmail(ImapClient ic, DataRow Dt)
{
try
{
ic.SelectMailbox("Inbox");
Lazy<MailMessage>[] mm = ic.SearchMessages(SearchCondition.SentSince(Convert.ToDateTime("1/10/2016 11:48:59 AM")), false, true)
InsertIMAP ObjectIMAPInsert = new InsertIMAP();
ObjectIMAPInsert.InsertEmail(mm, Dt);
#region "Get email code"
//foreach (Lazy<MailMessage> message in mm)
//{
// MailMessage m = message.Value;
// string FromAddress= m.From.Address;
//}
#endregion
ic.Dispose();
}
catch (Exception ex)
{
ErrorHandling.ErrorLog(string.Format("Method:LoadIMAP, LineNumber:{0}, Source:{1}, Message:{2}", ex.StackTrace, ex.Source, ex.Message));
}
}
}
}
Here in this code when i am trying to execute
Lazy<MailMessage>[] mm = ic.SearchMessages(SearchCondition.SentSince(Convert.ToDateTime("1/10/2016 11:48:59 AM")), false, true)
it throws an exception like
xm007 bad command argument 11
Can anybody guide to solve this?
Related
Exception snapshot
enter image description here
STEP A=>Validating the proper certificate configuration
I have a window service via which i am trying to connect the LDAP server from secure port 636 (SSL), all the certificate are properly
configured and i have verified this using the tool ldap.exe and also check the portqry tool to check if the port 636 is listening or not
and was successful in doing that.
STEP B=>Code Snippet Which is not working for secure port 636(For SSL) but working correctly with non secure port (389) A strange
observation the Below code works well when i run it as console based
application even with port 636 but fails when run as window service.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace SampleLDAPWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TestDirectoryEntryWay();
}
protected override void OnStop()
{
}
}
public DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = null;
ldapConnection = new DirectoryEntry("LDAP://abc.domain.com:636", "DomainAdmin", "DomainAdmin123", AuthenticationTypes.SecureSocketsLayer);
return ldapConnection;
}
public void TestDirectoryEntryWay()
{
DirectorySearcher _searcher = null;
SearchResult result_user = null;
DirectoryEntry de = createDirectoryEntry();
try
{
object o = de.SchemaEntry;//Getting a com exception as the SchemaEntry is null not sure why as the same is working properly in port 389
_searcher = new DirectorySearcher(de, "(&(objectClass=user)(SAMAccountName=" + "demouser1" + "))");
if (_searcher != null)
{
result_user = _searcher.FindOne();
}
}
catch (Exception ex)
{
//Getting a com exception
}
}
}
}
STEP C=>Code which is working in both port 636 and port 389 in window service
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace SampleLDAPWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
// TestDirectoryEntryWay();
var isLogged2 = SignInLDAP2("DomainAdmin", "DomainAdmin123", ""LDAP://abc.domain.com:636"", "abc.domain.com", true);
}
protected override void OnStop()
{
}
public bool SignInLDAP2(string user, string psw, string ldapPath, string domain = null, bool useSSL = false)
{
// LdapConnection ldapConnection = new LdapConnection(ldapPath);
var ldapDirectoryIdentifier = new LdapDirectoryIdentifier("abc.domain.com", 636, true, false);
LdapConnection ldapConnection = new LdapConnection(ldapDirectoryIdentifier);
if (useSSL)
{
ldapConnection.SessionOptions.SecureSocketLayer = true;
ldapConnection.AuthType = AuthType.Negotiate;
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
}
//var networkCredential = new NetworkCredential("Hey", "There", "Guy");
var networkCredential = new NetworkCredential(user, psw, domain);
try
{
ldapConnection.Bind(networkCredential);
bool exists = UserExists("demouser1");
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool UserExists(string username)
{
// create your domain context
using (PrincipalContext domain = new PrincipalContext(ContextType.Domain, "abc.domain.com", "DomainAdmin", "DomainAdmin123"))
{
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
}
}
}
}
QUESTION Here is
Is there a problem when working with Secure port with DirectoryEntry, as LdapConnection & networkCredential works smoothly with both the ports(636 &389),
i have a legacy code which uses DirectoryEntry and i want it work for secure port as well can some one please help me, how to make the STEP B working for secure port
also.
Thanks in Advance for all the Support & guidance.
It's likely that the SSL certificate isn't trusted by the computer you're running this on.
I use Chrome to test this. Run Chrome like this (adjust for the path your Chrome is in):
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=636
Then in Chrome, go to https://abc.domain.com:636. If the certificate is trusted, you'll see a "cannot connect" kind of message. But if it is not trusted, Chrome will give you a big red warning and you know that's the problem.
To trust the cert, you need to get the root certificate (as a file, likely *.cer or *.crt) and install it on every machine that will be running your code. Here are instructions for installing a root cert in Windows: https://www.thewindowsclub.com/manage-trusted-root-certificates-windows
I am trying to automate Outlook using COM, and we are having terrible problems with Outlook crashing at arbitrary points when trying to use MAPI methods (eg Outlook.Recipient r = MAPI.CreateRecipient("me#there.com")).
One solution that has been suggested is to use Marshal.GetActiveObject() instead of new Outlook.Application().
This appears to work fine, however I have run into a very strange issue - the code fires up a copy of outlook and tries to get the application object, but calls to Marshal.GetActiveObject throw a System.Runtime.InteropServices.COMException exception while Outlook is the active application (Has the focus).
If I run the below code, the try keeps failing over and over.
However, if I hit ALT-TAB or click anywhere such that Outlook is no longer the active application, the code INSTANTLY succeeds.
Any ideas why? Failing that, does anyone have code that will de-focus outlook, so the code succeeds?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;
namespace MAPI_Repro
{
class FakeTest
{
public Outlook.Application oApp;
public Outlook.NameSpace MAPI;
public void DoTest(){
if (Process.GetProcessesByName("OUTLOOK").Count() == 0)
{
var process = Process.Start(new ProcessStartInfo("outlook.exe"));
}
while (Process.GetProcessesByName("OUTLOOK").Count() == 0)
{
Thread.Sleep(100);
}
bool success = false;
while (!success)
{
Debug.WriteLine("Waiting for Marshal.GetActiveObject");
try
{
// This FAILS while Outlook is the active application.
// As soon as you hit ALT-TAB or click another app, this succeeds.
oApp = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
success = true;
Debug.WriteLine("SUCCESS");
}
catch (System.Runtime.InteropServices.COMException exp)
{
Debug.WriteLine("FAILED " + exp);
}
Thread.Sleep(100);
}
MAPI = oApp.GetNamespace("MAPI");
MAPI.Logon("", "", Missing.Value, Missing.Value);
}
}
}
I have been following the example below to send email using C# code with success:
MSDN Mail Message
However, I would like the code to display the composed email message on user machine, so that user can have a final check before hitting send button on outlook.
In the VBA world, I can use mail.Display in place of mail.Send.
Can anyone provide some advice to achieve that in C#?
Thanks.
How about this...
private void btnEmail_Click(object sender, EventArgs e)
{
string command = "mailto:somebody#domain.com?subject=The Subject&bcc=another#codegaim.com&body=Hi,I found this website and thought you might like it http://www.geocities.com/wowhtml/";
Process.Start(command);
}
Found a great solution to my problem i.e. to use Microsoft Office Interop Outlook instead of System.Net.MailMessage
followed this:
How to send a mail using Microsoft.Office.Interop.Outlook.MailItem by specifying the From Address
//using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Outlook;
namespace ConsoleApplication1
{
using Outlook = Microsoft.Office.Interop.Outlook;
public static class Program
{
static void Main(string[] args)
{
SendUsingAccountExample();
}
private static void SendUsingAccountExample()
{
var application = new Application();
var mail = (_MailItem)application.CreateItem(OlItemType.olMailItem);
mail.Body = "Hello";
mail.Subject = "Good Bye";
mail.To = "hello#google.com";
// Next 2 lines are optional. if not specified, the default account will be used
Outlook.Account account = Application.Session.Accounts["MyOtherAccount"];
mail.SendUsingAccount = account;
mail.Display(false); // To Display
//mail.Send(); // To Send
}
}
}
I wanted to access over IMAP to my gmail account bsed on this example:
http://code.msdn.microsoft.com/windowsdesktop/Simple-IMAP-CLIENT-b249d2e6
When I start to debug the code, I get always an error at the codeline:
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
It gives me the error:
"The requested service provider could not be loaded or initialized"
My search on Internet give me as result, that I need to repair the Window Socket.
But, when I run directkly the compiled .exe file, then I don't get this error at all.
This makes no sense to me.
Does anybody have an idea, whats wrong here?
The code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace IMAP
{
class Program
{
static System.Net.Sockets.TcpClient tcpc = null;
static System.Net.Security.SslStream ssl = null;
static string username, password;
static void Main(string[] args)
{
username = "(username)";
password = "(password)";
SSLAuthenticate = "imap.gmail.com";
try
{
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
...
I am thankful for any help.
On our testing server, EWS autodiscover does not work. To eliminate an ill-set IIS option from the list of causes, I C&P'ed together a WindowsForms Application (code below) and put it, together with the Microsoft.Exchange.Webservice.dll, into a folder on which I have write permission.
Unfortunately, neither xml nor text file are created. Instead, I get an Unhandled Exception error.
System.NullReferenceException
at System.Windows.Forms.TextBoxBase.AppendText(String text)
This does not happen on my development machine, which is in the same AD domain and on which the test app always returns that autodiscover was successful.
Question: How come no Trace output is generated?
So now, my app code:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace ADDebugWin
{
public partial class Form1 : Form
{
public static string traceData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.TraceListener = new TraceListener();
// Optional flags to indicate the requests and responses to trace.
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
ews.TraceEnabled = true;
ews.UseDefaultCredentials = true;
try {
ews.AutodiscoverUrl("email#mydomain.com");
textBox1.AppendText("AutoDiscover erfolgreich.");
} catch (Exception ex) {
textBox1.AppendText(traceData);
textBox1.AppendText(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
TraceListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ADDebugMvc.Controllers;
using Microsoft.Exchange.WebServices.Data;
using System.Xml;
namespace ADDebugMvc.Models
{
class TraceListener : ITraceListener
{
public void Trace(string traceType, string traceMessage)
{
CreateXMLTextFile(traceType, traceMessage.ToString());
HomeController.traceData += traceType + " " + traceMessage.ToString() + "\r\n";
}
private void CreateXMLTextFile(string fileName, string traceContent)
{
// Create a new XML file for the trace information.
try
{
// If the trace data is valid XML, create an XmlDocument object and save.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(traceContent);
xmlDoc.Save(fileName + ".xml");
}
catch
{
// If the trace data is not valid XML, save it as a text document.
System.IO.File.WriteAllText(fileName + ".txt", traceContent);
}
}
}
}
One should note that
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
is not returning any Traces during AutoDiscover.
(ews.TraceFlags = TraceFlags.All; does.)
So no string is appended to traceData, which is why traceData==null -> Exception when appending it to a TextBox.