O365 using Mailkit to Delete mail? - c#

I have been working on this small console app to read through a mailbox. It works fine but after it has finished reading through the mails, I want it to move them to the Deleted post folder. I found other questions related to this, but it didn't seem to fix it. I don't get any errors and the Seen flag works flawless. Feel free to comment in case of questions.
DateTimeOffset test = DateTime.Now;
using (var client = new ImapClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("Imap.outlook.com", 993, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("Email#mail.com", "password");
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
for (int i = 0; i < inbox.Count; i++)
{
var message = inbox.GetMessage(i);
Console.OutputEncoding = System.Text.Encoding.ASCII;
test = message.Date;
inbox.AddFlags(i , MessageFlags.Seen, true);
inbox.AddFlags(i, MessageFlags.Deleted, true); // Doesn't do anything.
Console.WriteLine("Emne: {0}", message.Subject);
Console.WriteLine("Fra: {0}", message.From);
Console.WriteLine("id: {0}", test);
Console.WriteLine(" ");
}
Console.ReadLine();
client.Disconnect(true);
}

Hello i have found the answer, after alot of searching and testing,
inbox.AddFlags(i, MessageFlags.Deleted, true);
marked it for being deleted, but didn't move it to either Delete post or anything, I found that if i run the
inbox.Expunge();
it removes all the messages marked for being deleted.

Related

how to save email body into text file in c#

I'm trying to copy my inbox email to text file then search word in this text file. if this word exist i will use this word to query email-id from db finally forward this mail to this email-id.
my problem is i m not able to copy email into text file. msg variable always empty
this my code :
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("mymail#gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
for (int i = messageCount; i > 0; i--)
{
string msg = client.GetMessage(i).MessagePart.GetBodyAsText().ToString();
System.IO.File.WriteAllText(#"d:\\My File2.log", msg.ToString());
var body = System.IO.File.ReadLines(#"d:\\My File2.log");
if (body.Contains("cusotmer ID: X"))
{
getemailadress();
sendemail();
}
}
}
could you use this code :
var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage);
like this :
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("mymail#gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
for (int i = messageCount; i > 0; i--)
{
string msg = ASCIIEncoding.ASCII.GetString(client.GetMessage(i).RawMessage);
System.IO.File.WriteAllText(#"d:\\My File2.log", msg);
var body = System.IO.File.ReadLines(#"d:\\My File2.log");
if (body.Contains("cusotmer ID: X"))
{
getemailadress();
sendemail();
}
}
}
And, advice: stop call .ToString() for already string objects.
And i cannot understand why you trying to save messageBody to a TextFile. Because WriteAllText function will overwrite this file on each loop.
So you wont find your all message end of this method. You can find only last message body in the textfile. Are you noticed this?

MultiClient TCP server in C#

I've been developing a TCP server, and I require it to allow for the access of multiple clients at the same time.
I also require it to allow them to disconnect and reconnect whenever they wish and for whenever they send a TCP message for the logic to run behind it as well.
I have my basic code set up which allows for one user to be connected at once however, it doesn't allow for multiple clients.
Server Code - (First part, without logic)
IPAddress ipAd = IPAddress.Any;
TcpListener myList = new TcpListener(ipAd, 5001);
myList.Start();
Console.WriteLine("Waiting for a new connection");
Console.WriteLine("Last Connection From - " + client);
Console.Write("Stats - Errors: ");
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" " + Errors + " ");
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.WriteLine();
Console.WriteLine();
Console.Write(feed);
Socket s = myList.AcceptSocket();
client = Convert.ToString(s.RemoteEndPoint);
Console.Write(feed);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("\n Message Recieved");
string msg = "";
for (int i = 0; i < k; i++)
{
msg = msg + Convert.ToChar(b[i]);
}
feed = feed + " \n " + msg;
There is also client code which, I'm not going to put in here because I don't believe it's needed. If you have any questions or improvements/modifications about the client just ask/tell me and I'll take a look.
I've been told there is ways of doing it through another thread but I haven't got a clue to how I would approach it.

I am trying to send a text file to a mobile device via bluetooth using C#

I have searched the web but I am a newbie and I find it hard to understand everything clearly.
Here is the code I have reached so far:
In this part, I am storing the text files I desire to send in variables, the I am storing each mac address of each device along with the text file to be sent to this device in a 2D array.
an array cdevices is created to store the detected devices mac addresses in the range.
//Storing data.
var Sfile = #"C:\Users\Noha\Desktop\Shenawy.txt";
var Mfile = #"C:\Users\Noha\Desktop\Moustafa.txt";
var Nfile = #"C:\Users\Noha\Desktop\Noha.txt";
string[,] array = new string[3, 2]
{
{"7840E4FA48EB", Sfile},
{"502E5CBB1A4A", Mfile},
{"0017AB39CAD3", Nfile}
};
string[] cdevices = new string[3];
int x = 0;
//end of storing data
Here is a foreach loop that detects each device, and once the device is detected, a text file is supposed to be sent to that device.
//Check if the laptop's bluetooth i connectable
if (!BluetoothRadio.IsSupported)
System.Console.WriteLine("No Bluetooth device detected.");
if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
System.Console.WriteLine(BluetoothRadio.PrimaryRadio.Name.ToString());
System.Console.WriteLine(BluetoothRadio.PrimaryRadio.Mode.ToString());
BluetoothClient bc = new BluetoothClient();
//BluetoothDeviceInfo[] info = null;
//info = bc.DiscoverDevices(999);
BluetoothDeviceInfo[] devs = bc.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo device in devs)
{
//lstDevices.Items.Add(device.DeviceName + " - " + device.DeviceAddress);
cdevices[x] = device.DeviceAddress.ToString();
System.Console.WriteLine(device.DeviceName + " " + device.DeviceAddress.ToString());
device.Update();
device.Refresh();
device.SetServiceState(BluetoothService.ObexObjectPush, true);
if (!device.Authenticated)
{
// Use pin "0000" for authentication
if (!BluetoothSecurity.PairRequest(device.DeviceAddress, "0000"))
{
// MessageBox.Show("Request failed");
System.Console.WriteLine("Request failed");
}
}
for (int countOr = 0; countOr < 3; countOr++)
{
for (int countOc = 0; countOc < 3; countOc++){
if (cdevices[x] == array[countOr, countOc])
{
var uri = new Uri("obex://" + device.DeviceAddress + "/" + array[countOr,countOc+1]);
//ObexWebRequest req = new ObexWebRequest(uri);
var request = new ObexWebRequest(uri);
request.ReadFile(array[countOr, 1]);
var response = (ObexWebResponse)request.GetResponse();
System.Console.WriteLine(response.StatusCode.ToString());
//MessageBox.Show(response.StatusCode.ToString());
// check response.StatusCode
response.Close();
break;
}
}
}
x++;
}
However,the devices do not connect to the computer, and it says failure.
Also do I have to manually pair the devices?
Thank you
Okay so in case someone needs it , I have figured out why it gives a failure. The device needs to be already paired with the computer before starting. This has fixed it. However the part for sending the text file to the device is still not working

Retrieve command doesn't seem to work when trying to access mail from pop3 C#

When I connect to pop3.live.com the connection is fine and it also shows me the amount of messages I have and the size of the file but when I try and use "RETR" to get the messages and show them on a console application nothing is presented.
Here is what I have so far
string str = string.Empty;
string strTemp = string.Empty;
using (TcpClient tc = new TcpClient())
{
tc.Connect("pop3.live.com", 995);
using (SslStream sl = new SslStream(tc.GetStream()))
{
sl.AuthenticateAsClient("pop3.live.com");
using (StreamReader sr = new StreamReader(sl))
{
using (StreamWriter sw = new StreamWriter(sl))
{
sw.WriteLine("USER " + _username);
sw.Flush();
sw.WriteLine("PASS "+ _password);
sw.Flush();
sw.WriteLine("LIST");
sw.Flush();
sw.WriteLine("RETR");
sw.Flush();
sw.WriteLine("QUIT ");
sw.Flush();
while ((strTemp = sr.ReadLine()) != null)
{
if (strTemp == "." || strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
}
}
}
}
Console.WriteLine(str);
Console.ReadLine();
First you have to use the LIST command, which lists the message numbers. Then issue one or more RETR commands with a single message number from the previous list. Message numbers does not necessarily start from 1! See also my comment on your question about debugging this issue.
For example:
LIST
+OK 2 messages (4095)
1 710
2 3385
.
RETR 1
+OK 710 octets
Return-Path: <john#example.com>
...
With RETR, you need to specify which message to retrieve. RETR without a number is not supported per the POP3 specification.

Download Email Attachments from Outlook 2007

I am new 2 C# and i have been given a task...
I have to write a C# code to download the email attachments from outlook 2007 to a local drive or any specified location.The program should be in such a way that, given any username and password it should connect to that particular users outlook and download the files specified from a particular from address or subject line.
Any kind of help is appreciated.
So you are using outlook in an Exchange 2007/2010 environment? If yes you cold take a look at EWS.
Go through the following piece of code. It should work!
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
//Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);
inboxFolder = ns.GetDefaultFolder (Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
//subFolder = inboxFolder.Folders["MySubFolderName"];
//folder.Folders[1]; also works
//Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
//Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)inboxFolder.Items[i];
foreach (Microsoft.Office.Interop.Outlook.Attachments attachment in item.Attachments)
{
// Process the "attachment" object as per your requirement!
}
//Console.WriteLine("Item: {0}", i.ToString());
//Console.WriteLine("Subject: {0}", item.Subject);
//Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
//Console.WriteLine("Categories: {0}", item.Categories);
//Console.WriteLine("Body: {0}", item.Body);
//Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}

Categories