I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.
I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc. I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.
Hope this makes some amount of sense and that someone can shed some light on this. In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.
Mightytighty is leading you down the right path, but you shouldn't presume the type of encoding. This should do the trick:
var dataStream = view.ContentStream;
dataStream.Position = 0;
byte[] byteBuffer = new byte[dataStream.Length];
var encoding = Encoding.GetEncoding(view.ContentType.CharSet);
string body = encoding.GetString(byteBuffer, 0,
dataStream.Read(byteBuffer, 0, byteBuffer.Length));
I was having the same problem, but you just need to read it from the stream. Here's an example:
public string ExtractAlternateView()
{
var message = new System.Net.Mail.MailMessage();
message.Body = "This is the TEXT version";
//Add textBody as an AlternateView
message.AlternateViews.Add(
System.Net.Mail.AlternateView.CreateAlternateViewFromString(
"This is the HTML version",
new System.Net.Mime.ContentType("text/html")
)
);
var dataStream = message.AlternateViews[0].ContentStream;
byte[] byteBuffer = new byte[dataStream.Length];
return System.Text.Encoding.ASCII.GetString(byteBuffer, 0, dataStream.Read(byteBuffer, 0, byteBuffer.Length));
}
There is a simpler way:
public string GetPlainTextBodyFromMsg(MailMessage msg)
{
StreamReader plain_text_body_reader = new StreamReader(msg.AlternateViews[0].ContentStream);
return(plain_text_body_reader.ReadToEnd());
}
This works if the first alternative view is the plain text version, as it happens usually.
Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.
This great Codeproject article by Peter Huber SG, entitled 'POP3 Email Client with full MIME Support (.NET 2.0)' will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles.
You can use the Codeproject article as a start for writing your own parser, or appraise a library like SharpMimeTools, which is an open source library for parsing and decoding MIME emails.
http://anmar.eu.org/projects/sharpmimetools/
Hope this helps!
Related
I'm working with Exchange 2010 (not Exchange 2013 which lets the caller request both plain-text and HTML bodies directly).
To get HTML body, I'm using something like:
ExtendedPropertyDefinition PR_BODY_HTML = new ExtendedPropertyDefinition(0x1013, MapiPropertyType.Binary);
ExtendedPropertyDefinition PR_INTERNET_CPID = new ExtendedPropertyDefinition(0x3FDE, MapiPropertyType.Long);
PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties);
properties.RequestedBodyType = BodyType.Text;
properties.Add(EmailMessageSchema.Body);
properties.Add(PR_BODY_HTML);
properties.Add(PR_INTERNET_CPID);
...
byte[] htmlBodyBytes;
string htmlBody;
int iCP;
if (item.TryGetProperty<int>(PR_INTERNET_CPID, out iCP))
{
// The code never enters here
}
if (item.TryGetProperty<byte[]>(PR_BODY_HTML, out htmlBodyBytes))
{
htmlBody = Encoding.GetEncoding(65001).GetString(htmlBodyBytes);
}
string textBody = item.Body.Text;
For plain-text body, I get the correct string representation. But HTML body gives me just bytes and I don't know the codepage to pass to GetString. Currently, UTF-8's codepage is hardcoded but this won't work for production. I need to either find out the codepage of the HTML part or find another method of extracting it from the message. Of course, I could make a separate query to EWS setting RequestedBodyType = BodyType.HTML but I would better not make an additional query. I thought PR_INTERNET_CPID MAPI property (0x3FDE) will fit my needs but it's never populated (I double-checked that it exists on the mail server but I can't get it via EWS).
So I need to either convince Managed EWS library to return both HTML and plain-text as strings or get me PR_INTERNET_CPID value. What can I do for that?
OK, it turns out that PidTagInternetCodepage (PR_INTERNET_CPID) has type MapiPropertyType.Integer, not MapiPropertyType.Long (although MSDN says PT_LONG). After the adjustment, I can get the value in question just fine.
In c# is there possibility that rtsp video stream is used "System.net.httpwebrequest" if not plz tell me another alternative .
// the URL to download the file from
string basepath = #"rtsp://ip.worldonetv.com:1935/live/ ";
// the path to write the file to
// string sFilePathToWriteFileTo = "d:\\Download";
// first, we need to get the exact size (in bytes) of the file we are downloading
Uri url = new Uri(basepath);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
You can formulate RtspRequests with my library.
You can then base64 encode the RtspRequest and put that as the body to the HttpRequest.
Add the content-length header which would be equal to the length of the base64 encoded rtsp request in the body.
Add the header rtsp/x-tunneled to HttpRequest and then sent it along.
You should get back a HttpResponse with the body containing a base64 encoded RtspResponse.
Base64 decode the Body of the HttpResponse and then use the RtspResponse class in my library to parse it.
The library is # http://net7mma.codeplex.com/
And there is a codeproject article # http://www.codeproject.com/Articles/507218/Managed-Media-Aggregation-using-Rtsp-and-Rtp
If you need anything else let me know!
There's no standard C# library to do this. You can't even do it with the various .NET DirectShow wrappers. I just had a coworker spend a month on this problem and he ended up writing his own C# wrapper on GStreamer. If you're planning to display the video, the easiest option is to embed the VLC ActiveX control.
I want to send a mail with embeded image in ASP.NET
How can i do that?
Regards
Soner
There are generally two ways of doing this, whichever is preferred is up to you.
To literally "embed" the image in the email message itself, you'll want to add it as a Linked Resource and reference the attached resource in the email's HTML.
Alternatively, and more simply, if the image is hosted in a public location then you can just reference that location in the HTML of the email.
Based on the question, it sounds like you are preferring the former approach, but the latter is available as well.
MailAddress sendFrom = new MailAddress(txtFrom.Text);
MailAddress sendTo = new MailAddress(txtTo.Text);
MailMessage myMessage = new MailMessage(sendFrom, sendTo);
MyMessage.Subject = txtSubject.Text;
MyMessage.Body = txtBody.Text;
Attachment attachFile = new Attachment(txtAttachmentPath.Text);
MyMessage.Attachments.Add(attachFile);
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
emailClient.Send(myMessage);
I believe you can either attach the files and refer them, or alternatively, like in regular HTML, embed them encoded in Base64.
You can go through this link
http://www.dotnetspider.com/resources/41465-Send-Formatted-outlook-email-from-NET-C.aspx
Sample project is also attached.
It shows how to put the link of the image in the application in the html template and send emails.
I am just trying to write a multipart parser but things getting complicated and want to ask if anyone knows of a ready parser in C#!
Just to make clear, I am writing my own "tiny" http server and need to pars multipart form-data too!
Thanks in advance,
Gohlool
I open-sourced a C# Http form parser here.
This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.
This can be used as follows:
non-multipart
public void Login(Stream stream)
{
string username = null;
string password = null;
HttpContentParser parser = new HttpContentParser(stream);
if (parser.Success)
{
username = HttpUtility.UrlDecode(parser.Parameters["username"]);
password = HttpUtility.UrlDecode(parser.Parameters["password"]);
}
}
multipart
public void Upload(Stream stream)
{
HttpMultipartParser parser = new HttpMultipartParser(stream, "image");
if (parser.Success)
{
string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
string title = HttpUtility.UrlDecode(parser.Parameters["title"]);
// Save the file somewhere
File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
}
}
I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.
To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here
See my answer here for more information.
Check out the new MultipartStreamProvider and its subclasses (i.e. MultipartFormDataStreamProvider). You can create your own implementation too if none of the built in implementations are suitable for you use case.
With Core now you have access to a IFormCollection by using HttpContext.Request.Form.
Example saving an image:
Microsoft.AspNetCore.Http.IFormCollection form;
form = ControllerContext.HttpContext.Request.Form;
using (var fileStream = System.IO.File.Create(strFile))
{
form.Files[0].OpenReadStream().Seek(0, System.IO.SeekOrigin.Begin);
form.Files[0].OpenReadStream().CopyTo(fileStream);
}
I had a similar problem that i recently solved thanks to Anthony over at http://antscode.blogspot.com/ for the multipart parser.
Uploading file from Flex to WCF REST Stream issues (how to decode multipart form post in REST WS)
I previously used CDO.Message and CDO.Configuration in ASP Classic to create HTML emails which was VERY simple to do. In .NET, it appears that you have to give the System.Net.Mail.Message object an HTML string for the content and then somehow embed the required images. Is there an easy way to do this in .NET? I'm pretty new to .NET MVC and would most appreciate any help.
This is how it looks in ASP Classic:
Set objCDO = Server.CreateObject("CDO.Message")
objCDO.To = someone#somthing.com
objCDO.From = me#myaddress.com
objCDO.CreateMHTMLBody "http://www.example.com/somepage.html"
objCDO.Subject = sSubject
'the following are for advanced CDO schematics
'for authentication and external SMTP
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(cdoSendUsingMethod) = cdoSendUsingPort '2 - send using port
.Item(cdoSMTPServer) = mail.myaddress.com
.Item(cdoSMTPServerPort) = 25
.Item(cdoSMTPConnectionTimeout) = 10
.Item(cdoSMTPAuthenticate) = cdoBasic
.Item(cdoSendUsername) = "myusername"
.Item(cdoSendPassword) = "mypassword"
.Update
End With
Set objCDO.Configuration = cdoConfig
objCDO.Send
Basically I would like to send one of my views (minus site.master) as an email, images embedded.
I don't know of a simple way right off, but you could use WebClient to get your page, then pass the response as the body.
Example:
var webClient = new WebClient();
byte[] returnFromPost = webClient.UploadValues(Url, Inputs);
var utf = new UTF8Encoding();
string returnValue = utf.GetString(returnFromPost);
return returnValue;
Note: Inputs is just a dictionary of post variables.
One problem I think you'll run into right off is that I don't think you'd get the images. You could parse the HTML you get and then make the images absolute back to your server.
Thank you both for your help - here is a very clean and comprehensive tutorial posted by a .NET MVP
http://msdn.microsoft.com/en-us/vbasic/bb630227.aspx