How to update outlook mail body text before sending - c#

I am working on an Outlook add-in to handle email attachments by placing them on a server and putting a URL in the email instead.
One problem is that after adding the URL to the end of the email body the user's cursor is reset to the start of the email.
A related problem is that I do not know where the cursor is in the text so I cannot insert my URL into the correct location.
Here is some code showing what I am doing, for simplicity the code is assuming the body is plain text.
private void MyAddIn_Startup(object sender, System.EventArgs e)
{
Application.ItemLoad += new Outlook.ApplicationEvents_11_ItemLoadEventHandler(Application_ItemLoad);
}
void Application_ItemLoad(object Item)
{
currentMailItem = Item as Outlook.MailItem;
((Outlook.ItemEvents_10_Event)currentMailItem).BeforeAttachmentAdd += new Outlook.ItemEvents_10_BeforeAttachmentAddEventHandler(ItemEvents_BeforeAttachmentAdd);
}
void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
{
string url = "A URL";
if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML)
{
// code removed for clarity
}
else if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatRichText)
{
// code removed for clarity
}
else
currentMailItem.Body += attachment.DisplayName + "<" + url + ">";
Cancel = true;
}

Use Application.ActiveInspector.WordEditor to retrieve the Word Document object. Perform all the changes using Word Object Model.

This seems to do what I want:
using Microsoft.Office.Interop.Word;
void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
{
if (attachment.Type == Outlook.OlAttachmentType.olByValue)
{
string url = "A URL";
Document doc = currentMailItem.GetInspector.WordEditor;
Selection objSel = doc.Windows[1].Selection;
object missObj = Type.Missing;
doc.Hyperlinks.Add(objSel.Range, url, missObj, missObj, attachment.DisplayName, missObj);
Cancel = true;
}
}

Related

How can i verify existence signature in replying Outlook MailItem?

I have a mail (.msg), and i need to reply it. If user didn't set a signature for reply messages in Outlook, i'm creating default signature and appending it to a message body later.
public static MailItem CreateReplyMail(string mailPath, out string signature) {
signature = string.Empty;
try {
if(File.Exists(mailPath)) {
Application outlook = new Application();
var item = outlook.Session.OpenSharedItem(mailPath) as MailItem;
var replyMail = item.ReplyAll();
Inspector inspector = replyMail.GetInspector;
inspector.Activate();
return replyMail;
}
return null;
} catch(COMException e) {
//...
}
}
How can i verify existence signature in replying Outlook MailItem?
After inspector.Activate() in replyMail.Body i always have auto-generated text and signature, if user set it.
Use Document.Bookmarks.Exists("_MailAutoSig").

Sign into a webpage using default browser c#

I am trying to create a program that can login to a website through C#, but also using the default browser.
Currently, it works with the in-form browser fine, but I can't find the code to adapt it to work in an actual browser.
Any feedback is appreciated,
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace PortalLogin2
{
public partial class Form1 : Form
{
bool mHooked;
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
private void button1_Click(object sender, EventArgs e)
{
string input = "https://en-gb.facebook.com/";
Process.Start(input);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (mHooked) return;
HtmlDocument doc = webBrowser1.Document;
HtmlElement username = doc.GetElementById("email");
HtmlElement password = doc.GetElementById("pass");
HtmlElement submit = doc.GetElementById("u_0_");
string txtUser = "insert username here";
string txtPass = "insert password here";
doc.GetElementById("email").InnerText = txtUser.ToString();
doc.GetElementById("pass").InnerText = txtPass.ToString();
submit.InvokeMember("click");
mHooked = true;
}
}
}
Try www.seleniumhq.org
Selenium automates browsers. That's it! What you do with that power is
entirely up to you. Primarily, it is for automating web applications
for testing purposes, but is certainly not limited to just that.
Boring web-based administration tasks can (and should!) also be
automated as well.
It has support for C# and other languages.
It's possible to automate Internet Explorer by adding the COM references "Microsoft Internet Controls" and "Microsoft HTML Object Library".
Here is a working example to fill the field "email" on Facebook:
var ie = new SHDocVw.InternetExplorer();
ie.Visible = true;
// once the page is loaded
ie.DocumentComplete += (object pDisp, ref object URL) => {
// get the document
mshtml.HTMLDocument doc = (mshtml.HTMLDocument)(object)ie.Document;
// set the email field
mshtml.IHTMLElement email = doc.getElementById("email");
email.setAttribute("value", "na#na.na");
};
// naviagte to the page
ie.Navigate("https://en-gb.facebook.com/");
// wait indefinitely without blocking the current thread
new AutoResetEvent(false).WaitOne();

Adding forward text to email

I'm having a slight problem with adding text to forwarding emails. This is my current code:
private void ForwardFunction(Outlook.MailItem email)
{
Outlook.MailItem forwardEmail = ((Outlook._MailItem)email).Forward();
Outlook.Inspector forwardInsp = forwardEmail.GetInspector;
Word.Document forwardDoc = forwardInsp.WordEditor;
Word.Range forwardRange = forwardDoc.Range(0,1);
string forwardText = "This is some text";
forwardRange.Text = forwardText + forwardRange.text
newEmail.Recipients.Add("myemail");
forwardEmail.Save();
((Outlook._MailItem)forwardEmail).Send();
}
I've gone through it and it does add the text to the range, but when I receive the forwarded email it doesn't contain any of the additional text. I've used similar code to edit current emails that the user is editing (New, Replies/Forwards, InlineResponses) with success, but the email being passed to the function is the currently selected email in the inbox. Not sure if this matters, maybe because it's not being edited by the user.
I couldn't find a specific way to add new text to a programmatically forwarded email.
For anyone else interested in this, I ended up using the .HTMLBody. It seems that using the .GetInspector either gets the inspector of the _email instead of fEmail and you can't edit it or it gets the correct inspector but it can't edit it. Either way, using the .HTMLBody seems to get around it.
Outlook.MailItem fEmail = ((Outlook._MailItem)_email).Forward();
string forwardText;
forwardText = "class=MsoNormal>";
forwardText += "This is my forwarded message";
forwardText += "Bonus hyper link <a href='" + hyperlinkText + "'>" + hyperlinkText + "</a>";
var regex = new Regex(Regex.Escape("class=MsoNormal>"));
fEmail.HTMLBody = regex.Replace(fEmail.HTMLBody, forwardText, 1);
fEmail.Save();
fEmail.AutoForwarded = true;
((Outlook._MailItem)fEmail).Send();

c# asp.net send mail issue

I have create one web application where user can send friend request. If there are two users A and B. If A user send friend request to B then one pop up display's on B user dashboard. In that pop up box two buttons are there confirm or ignore.
If user click on confirm button then it takes some time to close that popup box. Because in backgroud it execute code for send email. Once email sent then that popup box close. So I want to close that popup box immediately after clicking on confirm button and then after send mail to that user.
Here is my code for accepting request and sending mail
#region dlUserFriendRequests_ItemCommand
protected void dlUserFriendRequests_ItemCommand(object source, DataListCommandEventArgs e)
{
HtmlTable objDataTable;
//Panel objDataTable;
switch (e.CommandName)
{
case "confirm":
RadioButtonList objRadioButtonList;
int intFriendRelationID = -1;
objRadioButtonList = (RadioButtonList)e.Item.FindControl("rblstFriends");
if (objRadioButtonList != null)
{
intFriendRelationID = UserManagementBL.AcceptUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID, objRadioButtonList.SelectedItem.Text);
if (intFriendRelationID > 0)
{
int SentByUserID = Convert.ToInt32(e.CommandArgument);
DataTable dtbSenderdetails = null;
string SenderEmail = "";
dtbSenderdetails = UserManagementBL.GetUserDetails(SentByUserID);
if (dtbSenderdetails != null)
{
SenderEmail = dtbSenderdetails.Rows[0]["UserName"].ToString();
SendConfirmationMail(SenderEmail);
Response.Redirect("~/Dashboard/Dashboard.aspx",false);
//GetUserFriendRequests();
}
}
}
break;
case "Ignore":
int intFriendRequestID = -1;
intFriendRequestID = UserManagementBL.IgnoreUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID);
GetUserFriendRequests();
break;
}
}
#endregion
#region Send confirmation mail
public void SendConfirmationMail(string email)
{
//DataTable dtblUserDetails = UserManagementBL.GetUserByUserName(email);
//if (dtblUserDetails != null)
//{
//int UserID = Convert.ToInt32(dtblUserDetails.Rows[0]["UserID"]);
//string FirstName = Convert.ToString(dtblUserDetails.Rows[0]["FirstName"]);
//string LastName = Convert.ToString(dtblUserDetails.Rows[0]["LastName"]);
string FirstName = this.LoginSessionDO.FirstName;
string LastName = this.LoginSessionDO.LastName;
var parameters = new System.Collections.Generic.Dictionary<string, string>();
parameters.Add("USER_NAME", string.Format("{0} {1}", FirstName, LastName));
parameters.Add("USER_IMAGE_URL", string.Format(SystemConfiguration.GetSiteURL() + "UserControls/UserPhoto.ashx?UserID={0}", this.LoginSessionDO.UserID));
string ToAddress = email;
string subject = FirstName + " " + LastName + " confirmed you as a friend on Lifetrons.";
CommonFunctions.CommonFunctions.SendEmail(SystemConfiguration.GetEmailSenderAddress(), ToAddress, subject, CommonFunctions.EmailTemplates.AcceptFriendRequest, parameters);
//}
}
#endregion
Here is my pop up box image
So how can I close that pop up box immediately after confirm button click? Is there any changes in my code?
You would do this in JavaScript. I assume you're already using AJAX to perform the Confirm action, otherwise it would just be reloading the page and your popup shouldn't be there anyway (since they're already confirmed?).
If you have jQuery on the frontend, you can use:
$('#confirm-box-id').hide();
Without jQuery, you could use:
document.getElementById('confirm-box-id').style.display = 'none';
Re-reading your message, it seems this is just a long running action. You should note that if you do hide this and don't show any indication of progress using the code above, for example, your user may navigate away or close the browser, which may cause the action to stop processing or be terminated forcefully server-side so the confirmation would never happen.

Cancel webclient Async request

Hopefully an easy question for you all but I'm really struggling.
I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.
Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)
private void searchCactus()
{
WebClient imgClient = new WebClient();
imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);
WebClient mwClient = new WebClient();
mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);
if (DeviceNetworkInformation.IsNetworkAvailable == false)
{
MessageBox.Show("No network found, please check network availability and try again");
}
else if (compoundSearchBox.Text.Contains("?"))
{
MessageBox.Show("\"?\" Not Permitted");
return;
}
else if (compoundSearchBox.Text != "")
{
progBar1.IsIndeterminate = true;
string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";
imgClient.OpenReadAsync(new Uri(#imageuri), imgClient);
mwClient.DownloadStringAsync(new Uri(#mwURI), mwClient);
// //lower keyboard
this.Focus();
}
else MessageBox.Show("Enter Search Query");
}
I tried implementing the following button but it does not work
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
imgClient.CancelAsync();
mwClient.CancelAsync();
}
as "the name 'mwClient' does not exist in the current context"
I would be very grateful if anybody could provide some guidance
Just put the two clients into fields in your class.

Categories