CDATA format string convert with MimeKit - c#

I have string data as CDATA Format. How can I convert this to Html or normal view text at C#? Should I use mimeKit or something else?
Received: from 172.19.76.148 (proxying for 85.105.234.193)
(InterKepWebMail authenticated user parkentegrasyon)
by kep.local with HTTP;
Mon, 29 Jan 2018 18:51:40 +0300
Content-Type: multipart/mixed;
boundary="------_=_NextPart_001_01F869E9.0A514C28"
Message-ID: <8ec68378-eca0-428d-a350-94427435a521.webmail#testkep.inter-kep.com.tr>
MIME-Version: 1.0
Date: Mon, 29 Jan 2018 18:51:40 +0300
From: "parkentegrasyon" <parkentegrasyon#testkep.inter-kep.com.tr>
To: <parkentegrasyon#testkep.inter-kep.com.tr>
Cc: <parkentegrasyon#testkep.inter-kep.com.tr>
Subject: =?utf-8?Q?=C3=96rnek_KEP_2018-01-29_18=3A51=3A41?=
User-Agent: InterKepWebMail/1.0.0
X-TR-REM-iletiTip: standart
X-TR-REM-iletiID:
--------_=_NextPart_001_01F869E9.0A514C28
Content-Type: text/html;
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
<b>Merhaba D=C3=BCnya!</b>
--------_=_NextPart_001_01F869E9.0A514C28
Content-Type: application/octet-stream;
name="test.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="test.txt"
dGVzdCBlaw==
--------_=_NextPart_001_01F869E9.0A514C28--

If you use MimeKit to parse the message, it will automatically decode the content (whether it be in base64 or quoted-printable).
In your example message, the text/html message body can be gotten like this:
var html = message.HtmlBody;
To get the decoded attachment content, you can do this:
foreach (var attachment in message.Attachments.OfType<MimePart> ()) {
using (var memory = new MemoryStream ()) {
attachment.Content.DecodeTo (memory);
var data = memory.ToArray ();
var text = Encoding.UTF8.GetString (data);
}
}

It's base64 encoded text. You can decode it like this
byte[] data = Convert.FromBase64String("dGVzdCBlaw==");
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
That prints 'Test ek'.

Related

MultipartFormDataContent.Add StringContent is adding carraige return/linefeed to the name

formData.Add(sJobId,"job_id"); is sending "job_id\r\n" to the server
Here is my C# method:
public static async Task UploadAsync(string url, int job_id, string filename, string filePath) {
try {
// Submit the form using HttpClient and
// create form data as Multipart (enctype="multipart/form-data")
using (var fileStream = new StreamContent(System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read)))
using (var formData = new MultipartFormDataContent()) {
StringContent sJobId = new StringContent(job_id.ToString());
StringContent sOthId = new StringContent(job_id.ToString());
// Try as I might C# adds a CrLf to the end of the job_id tag - so have to strip it in ruby
formData.Add(sOthId, "oth_id");
formData.Add(sJobId,"job_id");
fileStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formData.Add(fileStream, "dt_file", filename);
HttpResponseMessage response = await HttpClient.PostAsync(url, formData);
// If the upload failed there is not a lot we can do
return;
}
} catch (Exception ex) {
// Not a lot we can do here - so just ignore it
System.Diagnostics.Debug.WriteLine($"Upload failed {ex.Message}");
}
}
This is what my Ruby puma server is receiving - see how oth_id and job_id have \r\n appended but "dt_file" does not.
Parameters: {"oth_id\r\n"=>"42157", "job_id\r\n"=>"42157", "dt_file"=>#<ActionDispatch::Http::UploadedFile:0x007f532817dc98 #tempfile=#<Tempfile:/tmp/RackMultipart20190715-37897-189ztb6.msg>, #original_filename="2019-07-15 164600.msg", #content_type="application/octet-stream", #headers="Content-Type: application/octet-stream\r\nContent-Disposition: form-data; name=dt_file; filename=\"2019-07-15 164600.msg\"; filename*=utf-8''2019-07-15%20164600.msg\r\n">}
How do I stop the formData.Add appending a \r\n to the name?
The raw message the application is sending to the server is
POST https://example.com/ HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary="93655e5a-b6b3-48d6-82c9-0d9aa99164cc"
Content-Length: 522
--93655e5a-b6b3-48d6-82c9-0d9aa99164cc
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=oth_id
1234
--93655e5a-b6b3-48d6-82c9-0d9aa99164cc
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=job_id
1234
--93655e5a-b6b3-48d6-82c9-0d9aa99164cc
Content-Type: application/octet-stream
Content-Disposition: form-data; name=dt_file; filename=myfile.txt; filename*=utf-8''myfile.txt
a,b,c,d
aa,"b,b","c
c",dd
aaa
--93655e5a-b6b3-48d6-82c9-0d9aa99164cc--
Have a look at the name values.
Looking at RFC 7578 I can see in every example, that the value for name is always quoted.
Content-Disposition: form-data; name="user"
I did not find any hint if it is mandantory or not to quote the values, so I cannot judge who is wrong here.
To get such quoted name values you only have to quote the values in code.
public static async Task UploadAsync(string url, int job_id, string filename, string filePath) {
try {
// Submit the form using HttpClient and
// create form data as Multipart (enctype="multipart/form-data")
using (var fileStream = new StreamContent(System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read)))
using (var formData = new MultipartFormDataContent()) {
StringContent sJobId = new StringContent(job_id.ToString());
StringContent sOthId = new StringContent(job_id.ToString());
// Try as I might C# adds a CrLf to the end of the job_id tag - so have to strip it in ruby
formData.Add(sOthId, "\"oth_id\"");
formData.Add(sJobId,"\"job_id\"");
fileStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formData.Add(fileStream, "\"dt_file\"", filename);
HttpResponseMessage response = await HttpClient.PostAsync(url, formData);
// If the upload failed there is not a lot we can do
return;
}
} catch (Exception ex) {
// Not a lot we can do here - so just ignore it
System.Diagnostics.Debug.WriteLine($"Upload failed {ex.Message}");
}
}
which will now post this
POST https://example.com/ HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary="c33cdc86-db44-40ef-8e6e-3e13a96218d1"
Content-Length: 528
--c33cdc86-db44-40ef-8e6e-3e13a96218d1
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="oth_id"
1234
--c33cdc86-db44-40ef-8e6e-3e13a96218d1
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="job_id"
1234
--c33cdc86-db44-40ef-8e6e-3e13a96218d1
Content-Type: application/octet-stream
Content-Disposition: form-data; name="dt_file"; filename=myfile.txt; filename*=utf-8''myfile.txt
a,b,c,d
aa,"b,b","c
c",dd
aaa
--c33cdc86-db44-40ef-8e6e-3e13a96218d1--
Just found a pull request for PowerShell
// .NET does not enclose field names in quotes, however, modern browsers and curl do.
contentDisposition.Name = $"\"{LanguagePrimitives.ConvertTo<String>(fieldName)}\"";

How to add 'Name' header to embedded image in EmailMessage

I am trying to send an email with embedded image(Not as attachment file). I am able to send mail.
I'm sending mail using following code:
internal static void Send(SmtpServerConfigurations configurations, EmailMessage emailMsg)
{
using (var mail = InitializeMailMessage(emailMsg))
using (var smtpClient = CreateSmtpClient(configurations))
smtpClient.Send(mail);
}
private static MailMessage InitializeMailMessage(EmailMessage emailMsg)
{
var mail = new MailMessage
{
From = new MailAddress(emailMsg.From),
Subject = emailMsg.Subject,
IsBodyHtml = emailMsg.IsBodyHtml
};
mail.To.Add(emailMsg.To);
AddMessageBody(emailMsg, mail);
return mail;
}
private static void AddMessageBody(EmailMessage emailMsg, MailMessage mail)
{
if (emailMsg.IsBodyHtml)
{
var body = GetHtmlBody(emailMsg.Body, emailMsg.EmbeddedImages);
mail.AlternateViews.Add(body);
}
else
mail.Body = emailMsg.Body;
}
private static AlternateView GetHtmlBody(string body, List<EmbeddedImage> embeddedImages)
{
var alternateView = AlternateView.CreateAlternateViewFromString(body, null,
MediaTypeNames.Text.Html);
if (embeddedImages == null) return alternateView;
foreach (var image in embeddedImages)
{
var imageToInline = new LinkedResource(image.Path, MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = image.Id;
alternateView.LinkedResources.Add(imageToInline);
}
return alternateView;
}
private static SmtpClient CreateSmtpClient(SmtpServerConfigurations config)
{
var smtpClient = new SmtpClient(config.Host);
smtpClient.Port = config.PortNo;
if (config.IsAuthenticationRequired)
smtpClient.Credentials =
new NetworkCredential(config.Username, config.Password);
else
smtpClient.UseDefaultCredentials = true;
smtpClient.EnableSsl = false;
return smtpClient;
}
But the mail sent using above code is not in the format as I want.
What I want is;
MIME-Version: 1.0
From: x#y.com
To: a#b.com
Date: 11 Nov 2016 11:37:52 +0530
Subject: This is subject
Content-Type: multipart/related;
boundary=--boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d; type="text/html"
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE html PUBLIC " -//W3C//DTD XHTML 1.0 Transitional//EN" "=
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xm=
lns =3D "http://www.w3.org/1999/xhtml" > <head ><meta http - equi=
v =3D "content-type" content =3D "text/html; charset=3DUTF-8" /><=
/head ><body style =3D"font-family: Segoe UI; text-align:left;" >=
This is body<br /><img alt =3D"" src =3D"cid:05393c56-15c1-4652-a=
31f-9cc513726bc0" height=3D"50" width=3D"50"/></body ></html >
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d
Content-Type: image/jpeg name="filename.jpg" <<-----This is what I want.
Content-Transfer-Encoding: base64
Content-ID: <05393c56-15c1-4652-a31f-9cc513726bc0>
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMF
BwYHBwcGBwcI
.
.
.
/w20K7sPt8ul2st3/z0dd36Hj9K9I+HHwj8M6/rLaldaJp8l6y
kGRYgn6LgfpXve0pundwQmk9z//Z
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d--
What I am getting is;
MIME-Version: 1.0
From: x#y.com
To: a#b.com
Date: 11 Nov 2016 11:37:52 +0530
Subject: This is subject
Content-Type: multipart/related;
boundary=--boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d; type="text/html"
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE html PUBLIC " -//W3C//DTD XHTML 1.0 Transitional//EN" "=
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xm=
lns =3D "http://www.w3.org/1999/xhtml" > <head ><meta http - equi=
v =3D "content-type" content =3D "text/html; charset=3DUTF-8" /><=
/head ><body style =3D"font-family: Segoe UI; text-align:left;" >=
This is body<br /><img alt =3D"" src =3D"cid:05393c56-15c1-4652-a=
31f-9cc513726bc0" height=3D"50" width=3D"50"/></body ></html >
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-ID: <05393c56-15c1-4652-a31f-9cc513726bc0>
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMF
BwYHBwcGBwcI
.
.
.
/w20K7sPt8ul2st3/z0dd36Hj9K9I+HHwj8M6/rLaldaJp8l6y
kGRYgn6LgfpXve0pundwQmk9z//Z
----boundary_3_1bb3db0a-d33f-46a7-a6ce-60249096160d--
How can I achieve that custom "Name" header in Embedded image section of raw mail?
I want to add that header is because;
When I click on download button shown on image in Gmail inbox, I get "noname" file without extension. That downloaded file isn't useful unless user changes its extension to '.jpg/.jpeg'.
When I tried the same with another component(Which I don't have code for) strangely I was able to download that image with correct filename. Only difference between these two mails was "Name" header.
Please suggest me how to do this or any other way to achieve it.
This will do the trick for you
imageToInline.ContentType.Name = "ImageName.jpg";

Why I can't read the ResponseHeaders of this downloaded page with WebClient?

This is the page I want to analize (which is iso-8859-1):
http://www.unione.tn.it/cms-01.00/articolo.asp?IDcms=20488
So if you look at the source code:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
This is my code:
using (WebClient client = new WebClient())
{
client.Headers.Add("user-agent", HttpContext.Current.Request.UserAgent);
var rawBytes = client.DownloadData(HttpUtility.UrlDecode(resoruce_url));
var contentType = new ContentType(client.ResponseHeaders["Content-Type"]);
Response.Write(client.ResponseHeaders);
}
but it prints:
Content-Length: 22967
Content-Type: text/html
Date: Fri, 17 Jan 2014 14:24:17 GMT Expires: Fri, 17 Jan 2014 14:24:16 GMT
Set-Cookie: Lang=1; expires=Fri, 16-Jan-2015 23:00:00 GMT; path=/,ASPSESSIONIDACCAQTTC=PGGNBKJAHLBBCMELCOMHMHJG; path=/
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Cache-control: private
Content-Type is text/html. It has lost iso-8859-1.
Why? And how can I get it?
If you want to get charset value (page encoding) you could try this
Encoding encoding = null;
using (WebClient client = new WebClient())
{
string html = client.DownloadString(websiteUrl);
encoding = doc.DetectEncodingHtml(html);
}

Reading multipart content from raw http request

I am saving a raw HTTP request to a text file and I need to read the multipart content within it. I know there are a number of 3rd party tools to do this but I need to do this with the .NET framework if possible. I have tried reading the txt file into a stream but I don't know how to extract the multipart content. Here is an example of the code I have been using and a sample file I am trying to read from :
var content = new MultipartFormDataContent();
var stream = new StreamContent(File.Open(#"C:\temp\test.txt", FileMode.Open));
content.Add(stream);
List<StreamContent> lstStreamContents = new List<StreamContent>();
if (content != null)
{
if (content.IsMimeMultipartContent())
await content.ReadAsMultipartAsync(StreamProvider);
foreach (MultipartContent multiPartContent in content)
{
foreach (var streamContent in multiPartContent).....
Text file :
Cache-Control: no-cache
Connection: Close
Content-Length: 5216
Content-Type: multipart/related;
boundary="cbsms-main-boundary";
start="<soap-envelope>", text/xml;
charset=utf-8
Accept: */*
Host: hostname
User-Agent: Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)
soapaction: ""
This is a multi-part message in MIME format.
--cbsms-main-boundary
Content-Type: text/xml;
charset="utf-8"
Content-ID: <soap-envelope>
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<mm7:TransactionID
xmlns:mm7="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL
-6-MM7-1-2">5947CCE35D5B4AEFB99DADDDF9472E67</mm7:TransactionID>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<mm7:DeliverReq
xmlns:mm7="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL
-6-MM7-1-2">
<mm7:MM7Version>6.5.0</mm7:MM7Version>
<mm7:MMSRelayServerID>hostname</mm7:MMSRelayServerID>
<mm7:LinkedID>1-1754394156</mm7:LinkedID>
<mm7:SenderAddress>
<mm7:Number>46707630767</mm7:Number>
</mm7:SenderAddress>
<mm7:Recipients>
<mm7:To>
<mm7:Number>72401</mm7:Number>
</mm7:To>
</mm7:Recipients>
<mm7:TimeStamp>2008-05-08 11:16:39</mm7:TimeStamp> <mm7:Priority>Normal</mm7:Priority>
<mm7:Subject>Tube test</mm7:Subject>
</mm7:DeliverReq>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
--cbsms-main-boundary
Content-Type: multipart/mixed;
boundary="cbsms-sub-boundary"
Content-ID: <MM7-Media>
--cbsms-sub-boundary
content-type: application/smil;
Name=main.smil;Charset=utf-8
content-transfer-encoding: 7bit
content-id: <AAAA>
content-length: 483
<smil><head><layout><root-layout backgroundColor="#FFFFFF"
background-color="#FFFFFF" height="480px" width="640px"/> <region id="Image" top="0" left="0" height="50%" width="100%" fit="meet"/> <region id="Text" top="50%" left="0" height="50%" width="100%"
fit="scroll"/>
</layout>
</head>
<body><par dur="4000ms"><img src="smslogo.jpg" region="Image"></img> <text src="smil.txt" region="Text"><param name="foreground-color"
value="#000000"/>
</text>
</par>
</body>
</smil>
--cbsms-sub-boundary
content-type: image/jpeg;
Name=smslogo.jpg
content-transfer-encoding: Base64
content-location: smslogo.jpg
content-length: 2218
/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAKgAA/+4ADkFkb2JlAGTAAAAA
Af/bAIQACwgICAgICwgICxAKCQoQEw4LCw4TFhERExERFhUREhISEhEVFRkaGxoZFSEhJCQh
ITAvLy8wNjY2NjY2NjY2NgEMCgoMDQwPDQ0PEw4ODhMUDg8PDhQaEhIUEhIaIhgVFRUVGCIe
IBsbGyAeJSUiIiUlLy8sLy82NjY2NjY2NjY2/8AAEQgAZgBmAwEiAAIRAQMR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3Y1drtdU0u4Y0W95BJgKAPbXvE1VwZ
XYtIPcNfAuCcN4+SSFNs14zBkz2jqcQh2/q6fzzrFvZaTLYNeDdXVG8MGpaytS526q5pbAuo
OlxA768C2WR2aQlx3nFWWNytoqjF11ZdHsYhG0MbsjaGjsS1K9j06zkuJDRzQRG07XOOwBYV
mt6xDGIYrl7YxgKUrTu7VXfJd3j89xI6V295JQ1uwba3lk/t5dz1+04rX5vO95YUlG3dH/bi
78cZM7W5uivvDG07+CSm6+g/NMHLz9QmJuuFdVHGGWQ40G5pGxARZ6B5WoU/25P8iSSoN2c9
HFMWXLPlaifVy+zTiy5T8rUj6qX2aSSebPbSFjyf06mfVTezT+5cm/1N3qpvZpJK5jtF7lyd
/U3eqm9mn9y5O/qZ9VN7NJJXM9s3uPKNcNTPqpfZpjZcr9GpH1Uvs0klc120DZ8u+TqP/HJ7
NO200QVz35MVPHpHJWnVRle8kkg9tq44+UfwJMxk38Bw4klJq5uM2mFOJ97/AIokkkp0+3p+
OD//2Q==
--cbsms-sub-boundary
content-type: text/plain;
Name=smil.txt;Charset=utf-8
content-transfer-encoding: 7bit
content-location: smil.txt
content-length: 9
Tube test
--cbsms-sub-boundary--
--cbsms-main-boundary--
At the moment I am getting this error 'Unable to cast object of type 'System.Net.Http.StreamContent' to type 'System.Net.Http.MultipartContent'.'
EDIT :
foreach (var part in multipart.Contents)
{
if (part.Headers.ContentType.MediaType == "multipart/mixed")
{
if (part.IsMimeMultipartContent())
await part.ReadAsMultipartAsync(StreamProvider);
foreach (MultipartContent multiPartContent in StreamProvider.Contents)
{
This gives the error ''Unexpected end of MIME multipart stream. MIME multipart message is not complete'
You are adding a StreamContent as a part to the empty MultipartFormDataContent. Naturally, ReadAsMultipartAsync then does nothing. Instead, you want to read the StreamContent. Also, your file contains not just the content, but the headers as well. If you snip off the headers, this ought to work:
using (var stream = File.Open (#"C:\temp\test.txt", FileMode.Open))
{
// note: StreamContent has no Content-Type set by default
// set a suitable Content-Type for ReadAsMultipartAsync()
var content = new StreamContent (stream) ;
content.Headers.ContentType =
System.Net.Http.Headers.MediaTypeHeaderValue.Parse (
"multipart/related; boundary=cbsms-main-boundary") ;
// TODO: make this recursive if required...
var outerMultipart = await stream.ReadAsMultipartAsync () ;
foreach (var outerPart in outerMultipart.Contents)
{
if (outerPart.IsMimeMultipartContent())
{
var innerMultipart = await outerPart.ReadAsMultipartAsync () ;
foreach (var innerPart in innerMultipart.Contents) // do stuff
}
else // do other stuff
}
}
Use HttpContentMultipartExtensions class and ReadAsMultipartAsync method
http://msdn.microsoft.com/en-us/library/hh835439%28v=vs.108%29.aspx
Good example is here:
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

Send multipart/signed email c#

I am trying to create a multipart/signed mime email following the RFC1847 protocol.
This is how it is supposed to look (part of the signature is removed):
Content-Type: multipart/signed; protocol="application/pkcs7-signature"
micalg=sha1; boundary="--PTBoundry=3"
----PTBoundry=3
Content-Type: multipart/mixed;
boundary="--PTBoundry=2"
----PTBoundry=2
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
TEST AF signed
----PTBoundry=2
Content-Type: application/octet-stream;
name=test2.txt
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename=test2.txt
bWludGVzdGF0dGFjaG1lbnRzaWduZWQ=
----PTBoundry=2--
----PTBoundry=3
Content-Type: application/pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
MIIKfAYJKoZIhvcNAQcCoIIKbTCCCmkCAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHAaCCCNow
ggPVMIICvaADAgECAgMCNtEwDQYJKoZIhvcNAQEFBQAwQjELMAkGA1UEBhMCVVMxFjAUBgNVBAoT
PrENekpgrYkz
----PTBoundry=3--
empty line
I cannot figure out how to actually send this as an email. I am using MailMessage and I have tried to add it as written below:
var stream = new MemoryStream(Encoding.ASCII.GetBytes(message));
var view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
however it does not work. The MailMessage adds different headers and messes it all up.
How can I send this correctly?
I am no longer using the MailMessage class, because I could not get it working.
Instead I am using EWS managed api like this:
var mail = new EmailMessage(_service);
mail.Subject = filename;
mail.MimeContent = new MimeContent("us-ascii", Encoding.ASCII.GetBytes(messageContentWithHeaders));
mail.SendAndSaveCopy();

Categories

Resources