What is "rfcTextOfMessage" value? : Google Apps Email Migration API Developer's Guide - c#

I am using Google API to test below code:
MailItemService mailItemService = new MailItemService(domain, "Sample Migration Application");
mailItemService.setUserCredentials(userEmail, password);
MailItemEntry entry = new MailItemEntry();
entry.Rfc822Msg = new Rfc822MsgElement(rfcTextOfMessage);
Referring to this Link .
I used Sample Value given for "rfcTextOfMessage".
But how to change To,Send and Date values for different mails?
Is there any way to get this format?
Note: I am using C#

In this example rfcTextOfMessage should be a string containing the actual email. If you're migrating messages this would simply be a string containing the entire raw message (headers, body, and encoded attachments) you want to load into google. The format of the message is rfc822; if you want to create a new message from scratch, or modify an existing one, simply edit the string (I'm not aware of any .Net classes which will output an rfc822 formatted string to make editing easier). If you're going to modify dates there's a tip here about doing that.

Related

Is the novell.directory.ldap c# library allready preventing ldap injection or do I have to encode potential user input by myself?

im currently developing a user interface to manage users and stuff. As data store I have to use a ldap. I'm using the novell.directory.ldap library for ldap related things.
I'm now wondering if this library already does encoding of parameters it is receiving, e.g. when performing a search, or if I have to encode potential user input, like usernames which will be later used in searchqueries, by myself.
I've already tried to do encoding with the AntiXSSLibrary (I'm using the nuget package sicne the ldap encoding was not included in the .net Framework itself like the other parts of the library) and its Encoder.LdapFilterEncode() and Encoder.LdapDistinguishedNameEncode() methods.
This is my code when trying to encode:
public static LdapSearchResults PerformSearch(LdapConnection connection, string filter, string basedn)
{
string encodedFilter = Encoder.LdapFilterEncode(filter);
string encodedBasedn = Encoder.LdapDistinguishedNameEncode(basedn);
LdapSearchConstraints searchConstraints = new LdapSearchConstraints { BatchSize = 0 };
return connection.Search(encodedBasedn, LdapConnection.SCOPE_SUB, encodedFilter, null, false, searchConstraints);
}
If I pass the parameters directly (= not encoded) everything will work as expected.
If I pass the encoded filter I will receive a LdapLocalException with message "Filter Error" at the Search() method of the LdapConnection instance.
If I pass the unencoded filter and pass the encoded basedn I will receive a LdapException with message "Invalid DN syntax" when trying to access the search results.
If I pass the unencoded filter and pass the ecoded basedn, in this case encoded with the Encoder.LdapFilterEncode() method, everything will work fine.
So the central question is: Do I have to worry about ldap injection or is the library already taking care about this threat? Unfortunately I couldn't find an answer for this in the documentation and by searching the web.
If I have to encode (what I'm expecting I have to do at the moment) what is the easiest and safest way to encode inputs for ldap in C#/.Net when the AntiXSSLibrary is not working for me?

Can I use a format string in a URL to navigate to web page, replacing the specified portion of the URL?

I'm interested in creating some sort of simple C# application takes a user string and passes it into a target portion of the URL. For example, since user query is visible in the page URL DuckDuckGo
Example:
https://duckduckgo.com/?q=web+browsers&ia=web
In this case, the URL shows that I searched for "web browsers". I would like the user to be able to pass any string to the application (via some kind of prompt that appears with the application is launched), and then launch a web browser and navigate to the target URL with the user input inserted into URL where the query is specified. (i.e., https://duckduckgo.com/?q=operating+systems&ia=web), where the user entered the string "operating systems".
So I would like to know which type of C# application to use that can interact with OS (Windows 10) and how to write the code for the the format String and the user prompt. Any guidance would be appreciated.
Your question is very broad so the best that can be done is give a broad answer. You mention "application" and "interact with the OS", so I'm assuming a native application, not a web app. A quick way to pull this off would be to Google for "C# Web Browser Example"; there are plenty of applications out there with well-explained source code that will answer your question:
So I would like to know which type of C# application to use that can
interact with OS (Windows 10)
As for the string replacement, Armine already pointed that out in his previous post. A simple textbox on your form, passed to some parsing code with string replacement, will do the trick for building the URL. The resulting URL is then passed to the web browser control you've used in your C# application; the URL will be one of the properties of the control.
The idea is to take what user typed as a string, and then create another string which will contain the words of that string, separated by the plus character (+)
String what_user_typed=" javascript jquery";
String query=what_user_typed.Replace(" ","+"); // A space represents a new word
String url="https://www.google.com/search?query="+query
After creating the url you can then use a webbrowser to open that url
I have not executed this but think this is what the logic should be.
string input = "operating system";
string destinationURL = $"https://duckduckgo.com/?q={input}&ia=web";
string formattedURL = HttpContext.Current.Server.UrlEncode(destinationURL);
System.Diagnostics.Process.Start(formattedURL);

HTML to Note content

When I trying to write some HTML text to Note, I have error (I think because HTML have some prohibited tags):
Evernote.EDAM.Error.EDAMUserException
When I use the same HTML with:
ENNote.Content = ENNoteContentAdvanced.NoteContentWithSanitizedHTML(HTML);
it works fine.
But I need get notes by ID, for updating. And I am not understand how I can write correctly HTML to Note (in HTML I have tables), or catching ENNote by GUID.
UPD.
I writing service for synchronization Notes (EN) between Evernotes and Microsoft Exchange Appointments (MA). When user create/update EN, my service create/update MA. When user update MA (created from Evernote), my service update EN. For linking I use EN GUID (I store it in MA in extended property). So I can find EN with this code:
List<ExtendedProperty> guids = appointment.ExtendedProperties.Where(ap => ap.PropertyDefinition == guidProp).ToList();
if (guids.Count > 0)
{
string guid = (string)guids.First().Value;
Note sNote = store.GetNote(guid, true, false, false, false);
}
But when I trying to set EN content I have error:
Error code "ENML_VALIDATION"
Parameter = "Document is invalid: no grammar found"
I can't store ENNoteRef in MA, because it object, not string. So I need to find ENNote by GUID (not ENNoteRef), or some stuff to set HTML to Note.Content without loosing tables.
It would help if you provide more of your code that surrounds the ENNote.Content call so we have more context.
Given the code you've provided: once you've created the ENNote and its content using the NoteContentWithSanitizedHTML function, you're then adding the note to the Evernote service with something like the following, correct?
ENNoteRef myNoteRef = ENSession.SharedSession.UploadNote(ENNote, null);
When you do this, you get back a NoteRef object, which is a reference to an actual specific note in the Evernote service. The NoteRef object has a Guid property, which is what you're looking for.

Cannot seem to add a custom text alternative view to my multipart email

I am writing a system to send out bulk emails to clients and for each site we store an HTML and Text version of the email so that if the users mail client doesn't support HTML the text view is still formatted correctly and as we want.
We don't want to just generate the plain text version from the HTML version as it adds in lots of menu links and other text which isn't formatted as we want.
This works fine in ASP classic with the Persits Email Component = http://www.aspemail.com/
as we add the HTML string as the Body and the text string as the AltBody.
However I am having trouble replicating this in C# .NET 4.5
I have followed as many examples as possible but my method that returns the MailMessage object which needs to pass the HTML looking for images/banners and then replace the URLS with ContentIDs and LinkedResources is somehow returning an email that looks great in HTML and Simple HTML View (in Thunderbird).
However whatever I do the plain text view seems to always be a version of the HTML that the object is trying to convert into text RATHER than the textual string we have pre-formatted and want to use.
If I debug the code I can see that the string is correct before I add it to the alternative view so I don't know what else I need to do.
In my method that parses the HTML, adds linked resources and returns a MailMessage object I have the following code:
<pre>
/* I pass in a custom SiteEmail object with 2 properties HTMLEmail and TextEmail that hold both versions of the email */
public MailMessage ParseEmailImages(SiteEmail siteEmail)
{
MailMessage email = new MailMessage();
// extract the HTML version as we need to parse it to swap URLs for ContentID/Resources and paths etc
string HTML = siteEmail.HTMLEmail;
// this is a generic list to hold all my picture resource objects that I find (swapping image URLs to paths and contentIDs)
List<LinkedResource> pictureResources = new List<LinkedResource>();
// code to find all the paths, create image resource objects and add them to my list - and modify the HTML to reference
// the new ContentIDs I swap the URLs for so the images are embedded in the email
// ..... code .....
// finished finding resource objects build email parts and return to caller
// Add each alternate view to the message.
// add the HTML view using my newly parsed HTML string
ContentType HtmlContentType = new ContentType("text/html; charset=UTF-8");
AlternateView altViewHTML = AlternateView.CreateAlternateViewFromString(HTML, HtmlContentType);
altViewHTML.TransferEncoding = TransferEncoding.QuotedPrintable;
// when I check here the siteEmail.TextEmail holds the CORRECT textual string I want BUT it's not displaying in the sent email
ContentType PlainContentType = new ContentType("text/plain; charset=UTF-8");
// as we didn't need to change anything in the text view we can just reference it straight out my custom email object siteEmail
AlternateView altViewText = AlternateView.CreateAlternateViewFromString(siteEmail.TextEmail, PlainContentType);
altViewText.TransferEncoding = TransferEncoding.QuotedPrintable;
// loop through all my picture resource objects and ensure they are embedded into the HTML email
foreach (LinkedResource pictureResource in pictureResources)
{
pictureResource.TransferEncoding = TransferEncoding.Base64;
altViewHTML.LinkedResources.Add(pictureResource);
}
// add both parts of the email (text/html) which are both alternative views to message
email.AlternateViews.Add(altViewText);
email.AlternateViews.Add(altViewHTML);
// return email object
return email;
}
// a very cut down example of the calling method
public bool SendEmail()
{
// parse our email object
MailMessage EmailMailMessage = this.ParseEmailImages(this.SiteEmail);
// send email
EmailMailMessage.From = new MailAddress(this.SendFromEmail, this.SendFromName);
EmailMailMessage.Subject = this.SendSubject;
// ensure encoding is correct for Arabic/Japanese sites and body transfer method is correct
EmailMailMessage.BodyEncoding = Encoding.UTF8;
EmailMailMessage.BodyTransferEncoding = TransferEncoding.QuotedPrintable;
SmtpClient client = new SmtpClient();
// this in a try catch and more complex
client.Send(this.EmailMailMessage);
}
</pre>
I have tried playing about with the encoding formats, just adding one alternative view and so on but cannot seem to get it to send out the same email as my old ASP Classic code e.g a multipart email with 2 boundaries, 1 for the text version WE WANT TO USE and one with the HTML version. It always seems to create it's own Plain Text version from the HTML version which I don't want to happen.
Any help or ideas would be much appreciated.
Thanks in advance for any help!
The answer seems to be that there is a bug in the MailMessage class. I have been told to report this as such on the Microsoft .NET forum.
It seems that the issue lies in the use of LinkedResources.
If I remove the code that adds the LinkedResources to the HTML alternative view then the code works fine and I can see both my Plain Text and HTML views in my mail client.
Therefore I have to leave the images as externally linked resources that are loaded into the email when the user presses any "load remote content" button in their email client.

What would be considered the best way to architect sending email from a C# web application?

I am working on a web application that will be going live soon, and I am now trying to figure out the best way for handling sending email from the application. I understand completely HOW to send email from the application using the MailMessage and SmtpClient classes, however my question is from a different angle. My main purpose at my job before this project was support of old applications that had been developed before my time. In these applications, when they needed to send email, they hard coded any of the messages into the actual message with all of the HTML tags embeded directly into the C# code.
The application that I am working on will have a template for the emails to be sent in, as a sort of styling container, and the different messages will be embeded into the main content div's of the template. I would like to avoid hardcoding these templates in this application, so I have been trying to figure out the best way to layout my project. I have thought of using a t4 template, and reading the different t4's into the application and applying a String.Format with the specified parameters to add names/emails to the messages to be sent. However, I am not sure this is the best way to do it.
My other idea was to define a class for each type of message, however this would end up hardcoding messages again, which as I said I don't want to do.
My question is, how have you approached this in the past? What worked, and what didn't and for what reasons? I have looked all over online, but either the only content out there is on HOW to send the message, or I have not used the right Google power words.
I do it this way:
Code it the usual way with ViewModel and Razor Template
By creating the e-mail, use http://razorengine.codeplex.com/ to load and parse the template
Be aware to not use Html and Url helper if you want to send e-mails in a thread, because they rely on HttpContext which you don't have in that case. Build your own helpers if needed.
For example, if you have a ViewModel Car in your application which is displayed somewhere, you could also use this ViewModel as #model in a Razor Template for e-mail.
I've had to do this on a couple of occasions. I originally used the ASP.Net template engine based on I think a Rick Strahl blog post. It worked but there was always some issue I was banging my head against.
I switched to using the NVelocity template engine and found it a really simple way to create and maintain email templates. There are a number of other template engines and I suspect next time I might have a serious look at the Razor engine.
The code for merging values into the template:
private string Merge(ManualTypeEnum manualType, Object mergeValues)
{
var body = "";
var templateFile = string.Format("{0}MailTemplate.vm", manualType);
var velocity = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty("file.resource.loader.path", Config.EmailTemplatePath);
velocity.Init(props);
var template = velocity.GetTemplate(templateFile);
var context = new VelocityContext();
context.Put("Change", mergeValues);
using (var writer = new StringWriter())
{
template.Merge(context, writer);
body = writer.ToString();
}
return body;
}
The values to merge are passed as an anonymous object, and can include various types including lists etc e.g.
var emailBody = Merge(newDocument.ManualType, new
{
ManualType = newDocument.ManualType.ToString(),
Message = change.Message,
NewTitle = newDocument.Title ?? "",
NewVersion = newDocument.Version ?? "",
Contact = From,
Changes = change.ToList(),
});

Categories