read outlook email in C# using pop3 (in korean) - c#

I want to read outlook email in C# using pop3.
when i get message from my mailbox, there is encoding exception because i read korean email.
how can i read korean email?
And Can i set mailbox that i want to read?
please help me
class Program
{
static Pop3Client client = new Pop3Client();
static StringBuilder builder = new StringBuilder();
static void Main(string[] args)
{
client.Connect("outlook.office365.com", 995, true);
client.Authenticate("blahblahblah", "blahblahblah");//로그인
Console.WriteLine("Checking Inbox");
DataTable table = new DataTable();
var count = client.GetMessageCount();//몇개의 메세지가 있는지
Console.WriteLine(count);
for (int i=count;i>=1;i--)
{
var message = client.GetMessage(i);
var fromAddress = message.Headers.From.Address;
var subject = message.Headers.Subject;
var messageBody = String.Empty;
var plainText = message.FindFirstPlainTextVersion();
if (plainText == null)
{
var html = message.FindFirstHtmlVersion();
messageBody = html.GetBodyAsText();
}
else
{
messageBody = plainText.GetBodyAsText();
}
table.Rows.Add(i,subject, fromAddress, messageBody);
}
}
}

Hi and welcome to Stack Overflow.
As per my understanding, you are using OpenPop.NET library.
OpenPop.NET uses EncodingFinder class to find correct encoding. By default it supports only utf8 and ascii (at least reading library code at github).
According to this page:
http://hpop.sourceforge.net/exampleChangeCharacterSetMapping.php
you can add your encoding(s) to EncodingFinder.
In your case, all you have to do is:
static void Main(string[] args)
{
EncodingFinder.AddMapping("ks_c_5601-1987", Encoding.GetEncoding(949));
// rest of the application
Please note this will work only on .NET Framework, not in .NET Core, since the latter supports a really limited number of encodings (https://learn.microsoft.com/en-us/dotnet/api/system.text.encodinginfo.getencoding?view=netcore-3.1).
I do not have a Korean pop3 on which to test this solution, but I hope it will work. Good luck!
Edit after some search
It should be possible to work with Korean encoding in .NET Core also, it's just a little trickier:
static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
EncodingFinder.AddMapping("ks_c_5601-1987", Encoding.GetEncoding(949));
// rest of application
Give it a try, if you are working with .NET Core.

Related

pop3 issue with trying to dowload attachments -C#

I have been looking high and low for a while to have an easy to use piece of code to have my C# project download a text file attachment on an email from gmail. I did take a look at openpop.net lib, which is the only library I see that seems promising! Can anyone show me some code that gets the job done? I looked at other peoples examples with openpop, but the api was different in their example, maybe older version? Thank you in advance for you help!
Here's how you would do this using my MailKit library which is vastly more efficient than OpenPOP.NET:
using System;
using System.Linq;
using MailKit.Net.Pop3;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
using (var client = new Pop3Client ()) {
client.Connect ("pop.gmail.com", 995, true);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("joey#gmail.com", "password");
int count = client.GetMessageCount ();
int unknown = 0;
for (int i = 0; i < count; i++) {
var message = client.GetMessage (i);
foreach (var attachment in message.Attachments.OfType<TextPart> ()) {
var fileName = attachment.FileName ?? string.Format ("unknown{0}.txt", ++unknown);
// Save the content of the attachment in whatever
// charset it is in.
using (var stream = File.Create (fileName))
attachment.ContentObject.DecodeTo (stream);
}
}
client.Disconnect (true);
}
}
}
}
If you have a lot of messages in your GMail account and/or you just want to download messages with even more efficiency, GMail supports the PIPELINING extension which MailKit can take advantage of.
Instead of downloading a single message at a time, you can use GetMessages() to batch request a range of messages which will take advantage of the PIPELINING extension which vastly reduces latency and thus can greatly reduce download times.

Email client app exceptions

I am developing an app with xamarin studio. My goal is to connect to pop3 and download emails to my app.
I am using the following code but I am facing these issues:
a) an exception on sslstream.AuthenticateAsClient("pop.gmail.com");. (The authentication or decryption has failed).
b)everywhere I have sw.Flush() I am taking exception: This operation is invalid until it is successfully authenticated.
TcpClient tcpclient = new TcpClient();
tcpclient.Connect("pop.gmail.com", 995);
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
sslstream.AuthenticateAsClient("pop.gmail.com");
StreamWriter sw = new StreamWriter(sslstream);
System.IO.StreamReader reader = new StreamReader(sslstream);
sw.WriteLine("USER myusername");
sw.Flush();
sw.WriteLine("PASS *****");
sw.Flush();
sw.WriteLine("RETR 1");
sw.Flush();
sw.WriteLine("Quit ");
sw.Flush();
string str = string.Empty;
string strTemp = string.Empty;
while((strTemp = reader.ReadLine()) !=null){
if(".".Equals(strTemp)){
break;
}
if(strTemp.IndexOf("-ERR") != -1){
break;
}
str +=strTemp;
}
reader.Close();
sw.Close();
tcpclient.Close();
EDIT
I used mailkit and it is a great solution. I can retrieve emails but i have a problem. When i have download a number of mails(not specific number. For deferent account was deferent number of mails)
I am taking the following error:
system.ArgumentOutOfRangeException on: var message = client.GetMessage(i, cancel.Token);
My code for the login:
partial void btnlogin (NSObject sender)
{
using (var client = new Pop3Client ()) {
var credentials = new NetworkCredential (Convert.ToString(txtusername.Text).Trim(), Convert.ToString(txtpassword.Text).Trim());
// Note: if the server requires SSL-on-connect, use the "pops" protocol instead
var uri = new Uri (Convert.ToString("pops://pop.gmail.com"));
using (var cancel = new CancellationTokenSource ()) {
client.Connect (uri, cancel.Token);
client.Authenticate (credentials, cancel.Token);
int count = client.GetMessageCount (cancel.Token);
var list= new List<string>();
for (int i = 0; i < count; i++) {
var message = client.GetMessage (i, cancel.Token);
Console.WriteLine ("From: {0}", message.From);
list.Add(Convert.ToString(message.From));
}
client.Disconnect (true, cancel.Token);
}
}
}
I came here to suggest using MailKit instead of writing your own library for this. MailKit is also specifically meant to work with Xamarin (since I work at Xamarin). MailSystem.NET is pretty badly broken (I've ranted about it elsewhere on StackOverflow), so I would definitely not recommend using that.
That said, you may need to look at using this version of the SslStream .ctor as opposed to the one you are using. The problem may be that the default .ctor isn't validating the SSL certificate because it isn't "trusted".
I would use an existing C# library to do this.
At one point in the past, I used MailSystem.NET and was able to port their library to MonoTouch. I am not sure of its license works for you, but you will have a much better time using it than rolling your own.
I also think that writing your own library for this would be a waste of anyone's time. I haven't tried Mail Kit yet (will definitely have to), but I have recently used Rebex Mail when I needed to backup my emails from my email server via POP3. Fortunatelly, it was a one time task only, so I did not have to pay as I only used their 30-day free trial that did not have any limitation.
using Rebex.Mail;
using Rebex.Net;
Pop3 client = new Pop3();
client.Connect("pop.gmail.com", SslMode.Implicit);
client.Login("gmailuser", "password");
var messageInfos = client.GetMessageList(Pop3ListFields.FullHeaders);
foreach (Pop3MessageInfo message in messageInfos)
client.GetMessage(message.SequenceNumber, string.Format(#"C:\gmail-pop3-backup\{0}-{1}.eml", message.Subject, message.UniqueId));
client.Disconnect();

WebSockets in firefox

For implementing my websocket server in C# I'm using Alchemy framework. I'm stuck with this issue. In the method OnReceive when I try to deserialize json object, I get a FormatException:
"Incorrect format of the input string." (maybe it's different in english, but I'm getting a localized exception message and that's my translation :P). What is odd about this is that when I print out the context.DataFrame I get: 111872281.1341000479.1335108793.1335108793.1335108793.1; __ad which is a substring of the cookies sent by the browser: __gutp=entrystamp%3D1288455757%7Csid%3D65a51a83cbf86945d0fd994e15eb94f9%7Cstamp%3D1288456520%7Contime%3D155; __utma=111872281.1341000479.1335108793.1335108793.1335108793.1; __adtaily_ui=cupIiq90q9.
JS code:
// I'm really not doing anything more than this
var ws = new WebSocket("ws://localhost:8080");
C# code:
static void Main(string[] args) {
int port = 8080;
WebSocketServer wsServer = new WebSocketServer(port, IPAddress.Any) {
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect,
OnConnected = OnConnected,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, 5, 0)
};
wsServer.Start();
Console.WriteLine("Server started listening on port: " + port + "...");
string command = string.Empty;
while (command != "exit") {
command = Console.ReadLine();
}
Console.WriteLine("Server stopped listening on port: " + port + "...");
wsServer.Stop();
Console.WriteLine("Server exits...");
}
public static void OnReceive(UserContext context) {
string json = "";
dynamic obj;
try {
json = context.DataFrame.ToString();
Console.WriteLine(json);
obj = JsonConvert.DeserializeObject(json);
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
}
On the C# side I'm using Newtonsoft.Json, though it's not a problem with this library...
EDIT:
One more thing - I browsed through the code in here: https://github.com/Olivine-Labs/Alchemy-Websockets-Example and found nothing - I mean, I'm doing everything the same way authors did in this tutorial...
EDIT:
I was testing the above code in Firefox v 17.0.1, and it didn't work, so I tested it under google chrome, and it works. So let me rephrase the question - what changes can be made in js, so that firefox would not send aforementioned string?
I ran into the same issue - simply replacing
var ws = new WebSocket("ws://localhost:8080");
with
var ws = new WebSocket("ws://127.0.0.1:8080");
fixed the issue for me.
In C# console app I connect the client to the server using :
var aClient = new WebSocketClient(#"ws://127.0.0.1:81/beef");
Your code above is connecting using
var ws = new WebSocket("ws://localhost:8080");
There could be one of two issues -
First is to see if WebSocketClient works instead.
To make sure your url is of the format ws://ur:port/context. This threw me off for a while.

AE.Net.Mail Imap partial fetch

I'm using C# and the AE.Net.Mail library to pull files from Gmail. I'm having problems with large zip files.
The same problem is described and resolved here with Java: JavaMail BaseEncode64 Error
Does anyone know how to set partial fetch flag with C# and the AE.Net.Mail library?
Go with (or take a look at) S22.Imap. It's an AE.Net.Mail documented with some extras.
From examples: Download attachments only if they are smaller than 2 Megabytes
using System;
using S22.Imap;
namespace Test {
class Program {
static void Main(string[] args)
{
using (ImapClient Client = new ImapClient("imap.gmail.com", 993,
"username", "password", Authmethod.Login, true))
{
// This returns all messages sent since August 23rd 2012
uint[] uids = Client.Search(
SearchCondition.SentSince( new DateTime(2012, 8, 23) )
);
// Our lambda expression will be evaluated for every MIME part
// of every mail message in the uids array
MailMessage[] messages = Client.GetMessages(uids,
(Bodypart part) => {
// We're only interested in attachments
if(part.Disposition.Type == ContentDispositionType.Attachment)
{
Int64 TwoMegabytes = (1024 * 1024 * 2);
if(part.Size > TwoMegabytes)
{
// Don't download this attachment
return false;
}
}
// fetch MIME part and include it in the returned MailMessage instance
return true;
}
);
}
}
}
}

Signing POST form in C# for uploading to Amazon S3

I am having trouble signing my policy documents for the Amazon S3.
There are examples on how to do it in Ruby, Java, and Python, but when I try to do it in C#, it's not working out. I keep getting an invalid signature, and I'm not sure where I'm going wrong.
http://aws.amazon.com/articles/1434
Can anyone provide an example like those in the article, except for C#?
Thanks.
Solved it for anyone else who runs into the same problem.
class Program
{
static string secretKey = "Removed";
static void Main(string[] args)
{
string policyStr = #"{""expiration"": ""2012-01-01T12:00:00.000Z"",""conditions"": [{""bucket"": ""<bucket>"" },{""acl"": ""public-read"" },[""eq"", ""$key"", ""<filename>""],[""starts-with"", ""$Content-Type"", ""image/""],]}";
GetSig(policyStr);
}
static void GetSig(string policyStr)
{
string b64Policy = Convert.ToBase64String(Encoding.ASCII.GetBytes(policyStr));
byte[] b64Key = Encoding.ASCII.GetBytes(secretKey);
HMACSHA1 hmacSha1 = new HMACSHA1(b64Key);
Console.WriteLine(policyStr);
Console.WriteLine(b64Policy);
Console.WriteLine();
Console.WriteLine(
Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(b64Policy))));
Console.ReadKey();
}
}

Categories

Resources