I'm trying to parse Email Subject which have encoding specified in format itself. I get the format and imagine how this can be done, but maybe there is any free .Net solution available already so I wouldn't waste time on it?
Here is an example of subject I want to parse:
=?ISO-8859-13?Q?Fwd=3A_Dvira=E8iai_vasar=E0_vagiami_da=FEniau=2C_bet_draust?=
I found a great library for parsing mentioned strings and whole mail in general - SharpMimeTools
It can't get mail from POP3 server on its own (I use OpenPop.Net for that) but it parses it nicely. Waay waaay muuuch better than OpenPop.Net parser
var popClient = new POPClient();
popClient.Connect("pop.test.lt", 110, false);
popClient.Authenticate("test#test.lt", "test");
// Get OpenPop.Net message
var messageInfo = popClient.GetMessage(1, false);
// Covert raw message string into stream and create instance of SharpMessage from SharpMimeTools library
var messageBytes = Encoding.ASCII.GetBytes(rawMessage);
var messageStream = new MemoryStream(messageBytes);
var message = new SharpMessage(messageStream);
// Get decoded message and subject
var messageText = message.Body;
var messageSubject = message.Subject;
I am one of the developer of OpenPop.NET, and as of now a new release have been made. You should not see any problems parsing any emails in OpenPop.NET anymore. If you find any - please let us at our mailing list.
We even implemented a test case for your specific subject - just to make sure.
Related
I'm working with C# on Windows servers for a web application stored on the IIS Server.
I would like to create an eml file from :
an html content (string)
some attachments that are loaded in memory
a string subject
string recipients
string sender
The main problem is that I am not allowed to store files on the host server (not even in a temporary directory or if I delete them after).
I saw many threads explaining how to create an eml file with the help of SmtpClient. But we always need to use a directory to save the file.
Do someone knows a way to do that ? Or to create a directory in memory (which seems undoable) ?
Thanks for everyone who will read me
[EDIT]
Using jstedfast's answer below and the Mime documentation, I could figure a way. Here is a POC in case someone needs it later.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey", "joey#friends.com"));
message.To.Add(new MailboxAddress("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder();
// Set the plain-text version of the message text
builder.TextBody = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
";
// We may also want to attach a calendar event for Monica's party...
builder.Attachments.Add("test.pdf", attachmentByteArray);
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody();
using (var memory = new MemoryStream())
{
message.WriteTo(memory);
}
Look into using MimeKit.
You can write the MimeMessage objects to any type of stream that you want, including a MemoryStream.
I use POP3 to receive email. But encoding error like, email's Subject "主题" turns to "涓婚". Chinese errors, strong text when the content of the text's language is English, no errors. Who can tell me, what should I do for it? The code below:
POP3 pop = new POP3();
pop.Connect("userName", "password", "pop.126.com", 110);//smtp.126.com
pop.DownloadMessages();
for (int i = 1; i < pop.Messages.Count; i++)
{
Email email = new Email();
Message msg = pop.Messages[i];
email.From = msg.From;
email.FromName = msg.FromName;
email.Body = msg.HTMLBody;
email.Title = msg.Subject;
}
I'm not sure what POP3 library you are using, but it is clearly broken and there's nothing you can do to "fix" your code to make it work beyond switching to another POP3 library, such as my MailKit library which is the only library that correctly handles charsets in all cases (most will handle Latin1 ok, but completely fail for CJK charsets).
The reason that most clients break for anything outside of Latin1 (ISO-8859-1) is that most email libraries have parsers that only work on strings. In order to convert the message data from bytes into a string, they need to pick a System.Text.Encoding (and most pick ISO-8859-1). They assume that email messages follow the rules outlined in the various RFCs that restrict email headers to US-ASCII, but it is very common for clients to ignore these rules.
Unlike those other parsers, MailKit's email parser parses byte streams and so does not require charset conversion before it can start parsing a message. This allows the parser to properly handle mixed charsets in the headers and body.
This is working fine locally but when I sent it to another person in the company (same exchange server) using Outlook on a mac, it does not work correctly. Instead, the image is replaced with the text ATT00001 and the image becomes an attachment called ATT0001
It was tricky to get this working in the first place, here is the code I use:
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("EmailManager.Kitten.jpg");
var inlineLogo = new LinkedResource(stream, "image/jpg");
inlineLogo.ContentId = "CompanyLogo";
body = body.Replace("{logourl}", string.Format("cid:{0}", inlineLogo.ContentId));
var view = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
view.LinkedResources.Add(inlineLogo);
mailMessage.Body = body;
mailMessage.Subject = "Check out the kitty logo";
mailMessage.AlternateViews.Add(view);
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(....);
smtp.Send(mailMessage);
The body is just a string of stuff with an <img src='{logourl}' /> in it.
Any suggestions of what I might do to fix or debug this? Alternatively is there a way to link to an external image without outlook blocking it by default (eg. having it come from the same server or similar).
Edit: I've read something about macs wanting the attachments listing at the end of the e-mail, could this be it? Although there is no way I can see from the above how to specify this behaviour. Also I am not entirely sure it's the problem.
can be one of the possible solution
i have found answer .bin file comes when _EmailLogo1 and
_EmailLogo are empty so need to check if it's empty/NULL or not !! if not empty/NULL then it should be linked otherwise don't !!
dynamic htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), null, "text/html");
if (!string.IsNullOrEmpty(_EmailLogo1)) {
LinkedResource logo = new LinkedResource(_EmailLogo);
logo.ContentId = "logo2";
htmlView.LinkedResources.Add(logo);
}
if (!string.IsNullOrEmpty(_EmailLogo))
{
LinkedResource logo1 = new LinkedResource(_EmailLogo1);
logo1.ContentId = "logo1";
htmlView.LinkedResources.Add(logo1);
aMessage.AlternateViews.Add(htmlView);
}
Some email clients are smart enough to display correctly whereas others require you to be very specific with your AlternateView and LinkedResource. Have you tried with other email clients e.g. Windows Live Mail?
Try specifying the ContentType of your AlternateView:
view.ContentType = new ContentType("text/html");
I had the same issue where Outlook did the same, displayed the image as an unnamed attachment however Windows Live Mail worked perfectly.
Fast forward to when we moved our SMTP server to Mandrill and we hit the same issue for all email clients where emails displayed as unnamed attachments and it turned out we didn't specify one of our ContentType's and it defaulted to "application/octet-stream"
I know that this question is a bit old, but I have noticed that some issues occur when you use ' instead of " wrapping the source.
Try instead to write it like this <img src="{logourl}" />
Hope this helps someone.
After lots of efforts I created my own mail parser. Now successfully able to parse and display emails. But few mails especially sent from apple or Iphone appear like this after parsing. I have no idea why this is happening. Please help.
=D8=AA=D9=88=D8= =A7=D8=AC=D9=87=D9=86=D9=8A =D9=85=D8=B4=D9=83=D9=84=D8=A9 =D8=A5=D8=B4=D8= =A7=D8=B1=D8=A9 =D9=84=D9=84=D9=83=D8=B1=D8=AA =D8=B1=D9=82=D9=85 410814189= 68 =D8=B9=D9=84=D9=85=D8=A7=D9=8B =D8=A8=D8=A3=D9=86 =D8=A5=D8=B4=D8=
It would appear that you mail parser does not handle decoding of Quoted Printable content.
I imagine that if you looked at the headers, you'd find a header like this:
Content-Transfer-Encoding: quoted-printable
I've written several email clients and multiple mime parsers and am currently working on writing a new mime parser in C# (the others were in C) called MimeKit here: http://github.com/jstedfast/MimeKit. This may be of interest to you...
I've got a filterable stream class that you can add a QuotedPrintableDecoder to (which I've also implemented), then pass your data through that to decode it. Or you could just pass it through the QuotedPrintableDecoder directly, depending on whatever is easiest for you.
Example usage:
var decoder = new QuotedPrintableDecoder ();
var output = new byte[decoder.EstimateOutputLength (input.Length)];
var outputLength = decoder.Decode (input, 0, input.Length, output);
// convert the output into a string displayable to the user...
var text = System.Text.Encoding.UTF8.GetString (output, 0, outputLength);
Obviously you'd use the proper System.Text.Encoding for the content (by looking at the "charset" parameter in the Content-Type header) instead of blindly using System.Text.Encoding.UTF8.
I have a requirement to send emails containing both text and Images.
So, I have .mhtml file that contains the content that needs to be emailed over.
I was using Chilkat for this, but in outlook 2007 it is showing the mhtml file as different attachments(html+images).
Can anyone suggest me some other component for sending mhtml emails.
FYI, I am using .Net 3.5
Also, I do not want to save the images on server before sending them.
Thank you!
I use plain old native MailMessage class. This previous answer can point you in right direction
EDIT: I built a similiar code some time ago, which captures an external HTML page, parse it's content, grab all external content (css, images, etc) and to send that through email, without saving anything on disk.
Here is an example using an image as an embedded resource.
MailMessage message = new MailMessage();
message.From = new MailAddress(fromEmailAddress);
message.To.Add(toEmailAddress);
message.Subject = "Test Email";
message.Body = "body text\nblah\nblah";
string html = "<body><h1>html email</h1><img src=\"cid:Pic1\" /><hr />" + message.Body.Replace(Environment.NewLine, "<br />") + "</body>";
AlternateView alternate = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
message.AlternateViews.Add(alternate);
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream("SendEmailWithEmbeddedImage.myimage.gif")) {
LinkedResource picture = new LinkedResource(stream, MediaTypeNames.Image.Gif);
picture.ContentId = "pic1"; // a unique ID
alternate.LinkedResources.Add(picture);
SmtpClient s = new SmtpClient();
s.Host = emailHost;
s.Port = emailPort;
s.Credentials = new NetworkCredential(emailUser, emailPassword);
s.UseDefaultCredentials = false;
s.Send(message);
}
}
System.Net would be the one that you are looking for.<br/>
MailMessage is used to compose new mail.<br/>
SMTPClient is used to send mail.
NetworkCredentials would be used to attach username and password for making request to sending mail.
Coming to your question how to add images.
You need to set isHtml=true for MailMessage
Since you want to send mail relative paths in the html won't work like ../directory/imagename.formate
in such case you need to give completed path to the image location that's websiteUrl/directory/imagename.formate
To get complete Url dynamically you can use like this Request.Uri.GetLeftParth(URIPartial.Authority)+VitrtualToAbsolute.getAbsolute("~")
I'm not sure about last line since I have wrote directly over here. You just need to use it and have good luck ;-)
You need to explicitly set the MIME type to multipart/related. Change the MailMessage.Body to include the content of the MHTML file in it. Finally add a new item to the MailMessage.AlternateViews collection to define the correct MIME type. The following link from MSDN has a very good example how to set it up:
MailMessage.AlternateViews Property