i need to recover all my message from my Outlook box. I use the OpenPop open source, but i can't recover the plain text (the value is null) and i don't understand why because when i check up my mail the plain text exist. When i try with the html version it works but i don't need this one in my project. Thanks to anyone who can help me.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using OpenPop.Mime;
using OpenPop.Pop3;
namespace EmailGmail
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string hostname = ***;
int port = **;
bool useSsl = true;
string username = ***;
string password = ***;
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(hostname, port, useSsl, username, password);
foreach (OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
}
}
public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using (Pop3Client client = new Pop3Client())
{
try
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
catch (Exception ex)
{
return null;
}
}
}
}
}
I had the same problem. I solved by going to pick the raw data of the body and using a method to convert its bytes to readable text (string).
string Body = msgList[0].MessagePart.MessageParts[0].GetBodyAsText();
Here is what you gets the body text.
msgList is the result of calling FetchAllMe messages, which gives you an array of messages. Every message has its MessagePart which contain the body text. Use GetBodyAsText to retrieve the body text. GetBodyAsText is already included in OpenPop library, so it's not a method of mine.
Hope this clears your doubts.
private void button7_Click(object sender, EventArgs e)
{
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(...);
StringBuilder builder = new StringBuilder();
foreach(OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
if(plainText != null)
{
// We found some plaintext!
builder.Append(plainText.GetBodyAsText());
} else
{
// Might include a part holding html instead
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
if(html != null)
{
// We found some html!
builder.Append(html.GetBodyAsText());
}
}
}
MessageBox.Show(builder.ToString());
}
Related
I try to write a UDP-Chat in C#.
I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them.
I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving.
is there a error in my code or is it a desing error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;
namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
string name = "testuser";
UdpClient receiveClient = new UdpClient(1800);
IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
public Chat_window(string name)
{
this.name = name;
fileWriter("Chat started", false); // write the initial start date in the errorfile
InitializeComponent();
Message_Load(); // starts the listen server theread
}
private void Message_Load()
{
lb_chat.Items.Add(name + " Joined the room...");
Thread rec = new Thread(ReceiveMessageFn);
rec.Start();
}
private void ReceiveMessageFn()
{
try
{
while (true)
{
Byte[] receve = receiveClient.Receive(ref receiveEndPint);
string message = Encoding.UTF8.GetString(receve);
if (message == name + " logged out...")
{
break;
}
else
{
if (message.Contains(name + " says >>"))
{
message = message.Replace(name + " says >>", "Me says >>");
}
ShowMessage(message);
}
}
//Thread.CurrentThread.Abort();
//Application.Current.Shutdown();
}
catch (Exception e)
{
//errorHandler(e);
}
}
private void ShowMessage(string message)
{
if (lb_chat.Dispatcher.CheckAccess())
{
lb_chat.Items.Add(message);// add Item to list-box
lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
lb_chat.UpdateLayout();
}
else {
lb_chat.Dispatcher.BeginInvoke(
new Action<string>(ShowMessage), message); // if list-box is not access able get access
return;
}
}
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
{
tb_eingabe.Text = "";
}
private void btn_submit_Click(object sender, RoutedEventArgs e)
{
submit_message();
}
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
submit_message();
}
}
void submit_message()
{
if (tb_eingabe.Text != "")
{
string data = name + " says >> " + tb_eingabe.Text;
SendMessage(data);
tb_eingabe.Clear(); // clear the textbox-values
tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
}
}
private void SendMessage(string data)
{
try{
UdpClient sendClient = new UdpClient();
Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
sendClient.Send(message, message.Length, endPoint);
sendClient.Close();
}
catch (Exception e)
{
errorHandler(e);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string data = name + " logged out...";
SendMessage(data); // send a logout message to the other chat peers
}
// debugging functions
static void errorHandler(Exception errorMsg)
{
MessageBox.Show(errorMsg.ToString()); // create a error-message-box
fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
}
static void fileWriter(string fileText, bool append)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
file.Close();
}
public static String GetTime(DateTime val)
{
return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
}
}
}
Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. See the example below:
IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);
IPAddress.Broadcast doesn't work in some network.
My application restarts when one iteration is over.
I need to send email when there's an exception in the code/application.
Let's say an exception has come in the application, I am sending an email.
1st iteration.. exception is sent in an email.
the application restarts the process.
2nd iteration.. when exception comes it has to check last sent email time.. if it is less than 30mins,don't send an email. If it is more than 30mins send email.
How can I code it such way?
I tried timers. that didn't work.
Here are few lines from the code.
catch (Exception ex)
{
Log("An exception has occured in the application: " + ex.Message);
exceptionMessage = ex.Message;
failureEmail = true;
SendFailureMail(exceptionMessage);
}
private void SendFailureMail(String message)
{
emailTime = DateTime.Now.ToString("h:mm");
//if (emailTime.Equals("00:00") || emailTime.Equals("1:00") || emailTime.Equals("2:00") || emailTime.Equals("3:00")
// || emailTime.Equals("4:00") || emailTime.Equals("5:00") || emailTime.Equals("6:00") || emailTime.Equals("7:00")
// || emailTime.Equals("8:00") || emailTime.Equals("9:00") || emailTime.Equals("10:00") || emailTime.Equals("11:00")
// || emailTime.Equals("12:00"))
//{
if (failureEmail)
{
eMailID = string.Empty;
subject = string.Empty;
mailBody = string.Empty;
eMailID = eMailIDFailure;
subject = eMailSubjectFailure;
emailBodyGeneric.Append(message);
mailBody = emailBodyGeneric.ToString();
if (sendmail())
{
Log("Mail Sent");
}
else
{
Log("Sending Mail Failed.");
}
}
}
Write the to a log file with an timestamp when the email was sent.
This can easily be accomplished.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
private static void LogEmailSent(DateTime date)
{
using(StreamWriter writer = new StreamWriter("my path"))
{
writer.WriteLine(date);
}
}
private static bool EmailSent()
{
bool logged = false;
//It is a good idea to include try catch and a good idea to check if the file exists;
if (!File.Exists("my file"))
return false;
using(StreamReader rdr = new StreamReader("my path"))
{
while(!rdr.EndOfStream)
{
string line = rdr.ReadLine();
DateTime dateLogged = Convert.ToDateTime(line);
TimeSpan difference = DateTime.Now.Subtract(dateLogged);
if(difference.TotalMinutes <= 30)
{
logged = true;
}
break; //the file contains a line, so try to parse the datetime;
}
}
return logged;
}
}
}
Remeber that is a an example. A lot of tweeking can be done.
I'm sending the contents of a few textboxes to my website using the HttpClient. My PHP script inserts the data in a database.
But after clicking the btnSubmit-button, it runs the code but nothing is added to my database and no exceptions are thrown. What's wrong with my code?
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Net.Http;
namespace PhoneApp2
{
public partial class Submit2 : PhoneApplicationPage
{
public Submit2()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("barcode", out parameter))
{
Barcode.Text = parameter;
}
}
public static int typeConnection()
{
switch (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType)
{
default:
return 0;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
return 2;
}
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
try
{
if (typeConnection() < 2)
{
string URI = "http://cocktailpws.net23.net/requests/add_contribution.php";
string myParameters = "barcode=" + Barcode.Text + "&booze=" + Name.Text + "&email=" + Email.Text;
sendData(URI, myParameters);
}
else
{
MessageBox.Show("No database connection could be established. Please check your internet connection and try again.");
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
public async void sendData(string URI, string myParameters)
{
using (HttpClient hc = new HttpClient())
{
var response = await hc.PostAsync(URI, new StringContent(myParameters));
}
}
}
}
PHP:
if(isset($_POST['barcode']) && isset($_POST['booze']) && isset($_POST['email'])){
include_once "../inc/inc_db.php";
$booze = sqlesc($_POST['booze']);
$barcode = sqlesc($_POST['barcode']);
$email = sqlesc($_POST['email']);
date_default_timezone_set('Europe/Amsterdam');
$date = date("Y-m-d H:i:s");
$query = "INSERT INTO contr_barcode(booze,barcode,email,datum) VALUES ('$booze','$barcode','$email',$date')";
if(mysqli_query($con,$query)){
echo "1";
}else{
echo "0";
}
}
You are sending the values formatted as if you are sending application/x-www-form-urlencoded however, by default StringContent will declare the content-type as text/plain. It is possible that the PHP framework is not parsing the content correctly because it thinks you are just sending unformatted plain text.
You could either change the content-type of the StringContent object, or you could use the UrlEncodedFormContent class. e.g.
var content = new StringContent(myParameters);
content.Headers.Content-Type = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await hc.PostAsync(URI, content);
I came across this article when trying to put together a reverse SSH solution in visual studio C#:
.NET SSH Port Forwarding
Using his code works up until the point where I actually start the port (port.Start()), then it throws an exception. Doing a reverse tunnel with PuTTY works just fine, so I believe the server is set up correctly. Am I doing something wrong in regards to implementing this SSH.NET library?
using Renci.SshNet;
using Renci.SshNet.Messages;
using Renci.SshNet.Common;
using System;
using System.Net;
using System.Threading;
namespace rSSHTunnelerSSHNET
{
public class Program
{
public static void Main(String[] arg)
{
String Host = "testserver.remote";
String Username = "testuser";
String Password = "password";
using (var client = new SshClient(Host, Username, Password))
{
client.Connect();
if (client.IsConnected)
{
Console.WriteLine("connected");
var port = new ForwardedPortRemote("targetserver.local", 80, "testserver.remote", 8080);
client.AddForwardedPort(port);
port.Exception += delegate(object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
port.Start();
}
else
{
Console.WriteLine("failed to connect.");
Console.ReadLine();
}
}
}
}
}
This is my code
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class s_TCP : MonoBehaviour {
internal Boolean socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "198.57.44.231";
Int32 Port = 1337;
string channel = "testingSona";
void Start () {
setupSocket();
//string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
string msg = "Sending By Sona";
writeSocket(msg);
readSocket();
}
void Update () {
//readSocket();
}
public void setupSocket() {
try {
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
}
}
public void writeSocket(string theLine) {
if (!socketReady)
return;
String foo = theLine + "\r\n";
theWriter.Write(foo);
theWriter.Flush();
}
public String readSocket() {
if (!socketReady)
return "";
if (theStream.DataAvailable){
string message = theReader.ReadLine();
print(message);print(12345);
return theReader.ReadLine();
}
else{print("no value");
return "";
}
}
public void closeSocket() {
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}
}
Connection created. But message not writing into server and reading
How can i do it
I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.
The following code does not work correctly:
public String readSocket() {
if (!socketReady)
return "";
if (theStream.DataAvailable)
return theReader.ReadLine();
return "";
}
This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:
theStream.ReadTimeout = 1;
And then, you can use something like:
public String readSocket() {
if (!socketReady)
return "";
try {
return theReader.ReadLine();
} catch (Exception e) {
return "";
}
}
This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.