Here is the problem:
use Attachment.SaveAsFile() to save contact's picture on disk.(successfully)
change the contact's picture in outlook manually.
repeat step 1, but i get the old picture, not the new one in step 2.
EDIT:
I have know how to save contact's picture on disk.
The problem is that the picture which i get is not the newest one.
Here is the code:
//[Outlook] is short for [Microsoft.Office.Interop.Outlook]
Outlook.Application outlook = new Outlook.Application();
Outlook.MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
foreach (var item in folder.Items) {
if (item is Outlook.ContactItem) {
Outlook.ContactItem contact = null;
Outlook.Attachments atts = null;
Outlook.Attachment att = null;
string path = "";
contact = item as Outlook.ContactItem;
if (!contact.HasPicture) { continue; }
path = #"C:\Temp\" + contact.EntryID + ".jpg";
atts = contact.Attachments;
att = atts["ContactPicture.jpg"];
if(File.Exists(path)){
File.Delete(path);
}
att.SaveAsFile(#"C:\Temp\" + contact.EntryID + ".jpg");
Marshal.ReleaseComObject(att);
att = null;
Marshal.ReleaseComObject(atts);
atts = null;
Marshal.ReleaseComObject(contact);
contact = null;
}
}
thanks!
I find the resolution on Contact picture retrieved via PIA doesn't change when updated in Outlook
I didn't release the folder.Items
Here is the modified codeļ¼
//[Outlook] is short for [Microsoft.Office.Interop.Outlook]
Outlook.Application outlook = new Outlook.Application();
Outlook.MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items items = null;
items = folder.Items;
foreach (var item in items) {
if (item is Outlook.ContactItem) {
Outlook.ContactItem contact = null;
Outlook.Attachments atts = null;
Outlook.Attachment att = null;
string path = "";
contact = item as Outlook.ContactItem;
if (!contact.HasPicture) { continue; }
path = #"C:\Temp\" + contact.EntryID + ".jpg";
atts = contact.Attachments;
att = atts["ContactPicture.jpg"];
if (File.Exists(path)) {
File.Delete(path);
}
att.SaveAsFile(#"C:\Temp\" + contact.EntryID + ".jpg");
Marshal.ReleaseComObject(att);
att = null;
Marshal.ReleaseComObject(atts);
atts = null;
Marshal.ReleaseComObject(contact);
contact = null;
}
}
if (items != null) {
Marshal.ReleaseComObject(items);
items = null;
}
EDIT:
Problem happened with above code. Sometimes it got the old picture.
I added GC.Collect(); at the end,then it worked well.
So i tried the following code. But the problem remained.
//[Outlook] is short for [Microsoft.Office.Interop.Outlook]
Outlook.Application outlook = new Outlook.Application();
Outlook.MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items items = folder.Items;
foreach (var item in items) {
if (item is Outlook.ContactItem) {
Outlook.ContactItem contact = item as Outlook.ContactItem;
string path = "";
Outlook.Attachment att = null;
if (!contact.HasPicture) { continue; }
path = #"C:\Temp\" + contact.EntryID + ".jpg";
att = contact.Attachments["ContactPicture.jpg"];
if (File.Exists(path)) {
File.Delete(path);
}
att.SaveAsFile(#"C:\Temp\" + contact.EntryID + ".jpg");
}
}
GC.Collect();
Finally i use the following code. Release all com objects,then call GC.Collect().
//[Outlook] is short for [Microsoft.Office.Interop.Outlook]
Outlook.Application outlook = new Outlook.Application();
Outlook.MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items items = folder.Items;
foreach (var item in items) {
if (item is Outlook.ContactItem) {
Outlook.ContactItem contact = null;
Outlook.Attachments atts = null;
Outlook.Attachment att = null;
string path = "";
contact = item as Outlook.ContactItem;
if (!contact.HasPicture) { continue; }
path = #"C:\Temp\" + contact.EntryID + ".jpg";
atts = contact.Attachments;
att = atts["ContactPicture.jpg"];
if (File.Exists(path)) {
File.Delete(path);
}
att.SaveAsFile(#"C:\Temp\" + contact.EntryID + ".jpg");
Marshal.ReleaseComObject(att);
att = null;
Marshal.ReleaseComObject(atts);
atts = null;
Marshal.ReleaseComObject(contact);
contact = null;
}
}
if (items != null) {
Marshal.ReleaseComObject(items);
items = null;
}
Marshal.ReleaseComObject(folder);
folder = null;
Marshal.ReleaseComObject(outlook);
outlook = null;
GC.Collect();
Related
we use Redemptiontools to develop a Addin for Outlook. At first we create Emailstubs from a Metadataset. When the User select a Mail we load a msg file from the Network and import it into the Emailstub. We dont have any problems in Outlook 2010/2013/2016.
But in Outlook 2007 the reading pane doesnt refresh if the mail has a Signature. I have deselect and reselect the Mail and then i can see the new mail.
Creating the Emailstub from an metadataset:
using (ComObjectWrapper<RDOFolder> rdoFolder = RDOSession.Resource.GetFolderFromID(folderEntryID).WithComCleanup())
{
using (ComObjectWrapper<RDOMail> mailstub = rdoFolder.Resource.Items.Add().WithComCleanup())
{
mailstub.Resource.Sent = true;
mailstub.Resource.SenderName = metadatamail.SenderName + " ";
mailstub.Resource.SenderEmailAddress = metadatamail.SenderEmailAddress + " ";
mailstub.Resource.SentOnBehalfOfName = metadatamail.SentOnBehalfOfName + " ";
mailstub.Resource.SentOnBehalfOfEmailAddress = metadatamail.SentOnBehalfOfEmailAddress + " ";
mailstub.Resource.Subject = metadatamail.Subject + " ";
mailstub.Resource.ReceivedTime = metadatamail.ReceivedTime;
mailstub.Resource.Body = metadatamail.Body + " ";
mailstub.Resource.To = metadatamail.To + " ";
mailstub.Resource.ReceivedByName = metadatamail.ReceivedByName + " ";
mailstub.Resource.UnRead = metadatamail.UnRead;
if (metadatamail.ContainsAttachments)
{
var Attach = mailstub.Resource.Attachments.Add(new char[0]);
Attach.FileName = "Attachment.txt";
}
mailstub.Resource.Save();
}
}
Importing the msg file in the selection change Event of the Explorer (expl):
void expl_SelectionChange()
{
using (var selection = expl.Selection.WithComCleanup())
{
foreach (var item in selection.Resource)
{
if (item is Outlook.MailItem)
{
string entryID = (item as Outlook.MailItem).EntryID;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
if (!string.IsNullOrEmpty(entryID))
{
using (var researchEntry = RDOSession.Resource.GetMessageFromID(entryID).WithComCleanup())
{
string mailpath = GetEmailFromNetwork(entryID);
if (!string.IsNullOrEmpty(mailpath))
{
Redemption.SafeMailItem sItem = new Redemption.SafeMailItem();
sItem.Item = researchEntry.Resource;
sItem.Import(mailpath, (int)rdoSaveAsType.olMSG);
sItem.ReleaseComObject<Redemption.SafeMailItem>();
researchEntry.Resource.Save();
}
}
}
}
}
}
}
RDOSession:
private ComObjectWrapper<RDOSession> RDOSession
{
get
{
try
{
var rdoSession = Activator.CreateInstance(Type.GetTypeFromProgID("Redemption.RDOSession")) as RDOSession;
if (rdoSession != null)
{
rdoSession.MAPIOBJECT = this.Application.Session.MAPIOBJECT;
return rdoSession.WithComCleanup();
}
}
catch { }
return null;
}
}
Does anyone have a hint or a solution?
I am working with a project where I am generating PDF Files from PSR Files. The PDF Files works fine if its a single page but if It has more than two PSR Files and I generate two files it does not open on iPad and works fine on Desktop.
The Third library tool I am using here is 'dbatuotrack' and I am using C#.
Can anyone please guide me how to resolve this problem?
Thanks,
S.
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
}
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}
}
objDoc = null;
objPage = null;
}
This how I tweaked the code to make it work. Thanks for the suggestion DJ KRAZE
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
}
}
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
//This region was the problem, disposing the output everytime.
//Needed it to be included after completion of iteration
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}
I m getting error when i m trying to send email to different Recipients with their respective attachment. i m using looping to change the Recipients and attachment but getting error. pls help to resolve this issue
my code is
private void BtnEmail_Click(object sender, EventArgs e)
{
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
if (RtxtBox.Text == "")
{
MessageBox.Show("Please set Mail body text");
GrpMailBody.Visible = true;
}
else
{
oMsg.HTMLBody = RtxtBox.Text;
}
if (RtxtSubject.Text == "")
{
MessageBox.Show("Please Enter Mail Subject");
GrpMailBody.Visible = true;
}
else
{
oMsg.Subject = RtxtSubject.Text;
}
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
for (int i = 0; i <= grvExcelData.RowCount; i++)
{
string EmaildID = grvExcelData.Rows[i].Cells[3].Value.ToString();
string sFileName = grvExcelData.Rows[i].Cells[5].Value.ToString()+".pdf";
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(EmaildID);
foreach (string fileName in fileEntries)
{
string fileN = "";
string xfileName;
xfileName=System.IO.Path.GetFileName(fileName);
if (xfileName == sFileName)
{
Outlook.Attachment oAttach = oMsg.Attachments.Add(#fileName, iAttachType, iPosition, sDisplayName); //getting error in this line
}
else
{
}
}
oRecip.Resolve();
oMsg.Send();
oRecip = null;
//oRecips = null;
oMsg = null;
oApp = null;
}
Add this--
Add reference Microsoft.Office.Interop.Outlook
using Outlook = Microsoft.Office.Interop.Outlook;
public void sendEMailThroughOUTLOOK()
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "Hello!!";
//Add an attachment.
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//now attached the file
Outlook.Attachment oAttach = oMsg.Attachments.Add(#"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);
//Subject line
oMsg.Subject = "Your Subject will go here.";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("EmailAddress");
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}//end of try block
catch (Exception ex)
{
}//end of catch
}//end of Email Method
Try to add Outlook Inspector as described here:
https://groups.google.com/forum/#!msg/microsoft.public.outlook.program_vba/lLJwbwwl-XU/gRuQYRpJtxEJ
using Outlook = Microsoft.Office.Interop.Outlook;
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMsg.GetInspector;
// ...
}
Using an application, I'm fetching the contact details stored in the Micosoft Office Outlook using C#. I achieved it through the Microsoft.Office.Interop namespace.
The issues I'm facing now is when Outlook has multiple mail IDs configured to the same system I need to fetch contacts of the Individual mail IDs seperately.
How do I do this?
Here is the sample code:
/// <summary>
/// Getting the contacts by passing the folder name.
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
private List<MyContact> GetContactsFromFolder(string folderName)
{
List<MyContact> contacts = null;
object missing = System.Reflection.Missing.Value;
//Create instance of Outlook application and Outlook Contacts folder.
try
{
OutLook.MAPIFolder fldContacts = null;
contacts = new List<MyContact>();
OutLook._Application outlookObj = new OutLook.Application();
/* if (folderName == "Default")
{
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
}
else
{
OutLook.MAPIFolder contactsFolder = (OutLook.MAPIFolder)
outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
//VERIFYING THE CUSTOM FOLDER IN OUT LOOK .
foreach (OutLook.MAPIFolder subFolder in contactsFolder.Folders)
{
if (subFolder.Name == folderName)
{
fldContacts = subFolder;
break;
}
}
}
* */
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
//LOOPIN G THROUGH CONTACTS IN THAT FOLDER.
foreach (Microsoft.Office.Interop.Outlook._MailItem contactItem in fldContacts.Items)
{
MyContact contact = new MyContact();
contact.FromAddress = contactItem.SenderEmailAddress;
contact.ToAddress = contactItem.To;
contact.Subject = contactItem.Subject;
contact.MailSize = contactItem.Size.ToString();
contact.Received = contactItem.ReceivedTime.ToString();
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Initial Catalog=sample;Integrated Security=True;Server=Test;Connect Timeout=900";
try
{
con.Open();
string to_address = "";
string Cc = "";
foreach (Microsoft.Office.Interop.Outlook.Recipient olRecipient in contactItem.Recipients)
{
if (contactItem.To.ToLower().Contains(olRecipient.Address.ToLower()) == true ||
contactItem.To.ToLower().Contains(olRecipient.Name.ToLower()) == true)
{
if (to_address != "")
{
to_address = to_address + ";" + olRecipient.Name + " <" + olRecipient.Address + ">";
}
else
{
to_address =olRecipient.Name+" <"+olRecipient.Address+">";
}
}
else
if (contactItem.CC != null && contactItem.CC.ToString() != "")
{
if (contactItem.CC.ToLower().Contains(olRecipient.Address.ToLower()) == true ||
contactItem.CC.ToLower().Contains(olRecipient.Name.ToLower()) == true)
{
if (Cc != "")
{
Cc = Cc + ";" + olRecipient.Name + " <" + olRecipient.Address + ">";
}
else
{
Cc = olRecipient.Name + " <" + olRecipient.Address + ">";
}
}
}
}
//contact.
contacts.Add(contact);
}
}
The point is in this call of your code:
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Here you are always opening the default folder.
You should try to enumerate the available folders and call another method of the Session object to open the one you need to use.
I don't know the answer right now, but this is the direction to go.
i want to save the contents of the Email Body in outlook to a file. I am able to save the entire message .msg but i want to save only the html content of the body.
for example:
In the outlook email body i have a table i want to save that table to a file.
the script which i am working on:
public void GetAttachments()
{
Microsoft.Office.Interop.Outlook.Application myolApp = default(Microsoft.Office.Interop.Outlook.Application);
Microsoft.Office.Interop.Outlook.NameSpace ns = default(NameSpace);
MAPIFolder Inbox = default(MAPIFolder);
object Item = null;
Attachment Atmt = default(Attachment);
string FileName = null;
string subject = null;
string AttachmentName = null;
string Body = null;
string SenderName = null;
string SenderEmailAddress = null;
string CreationTime = null;
int i = 0;
int j = 0;
try
{
myolApp = (Microsoft.Office.Interop.Outlook.Application)Interaction.CreateObject("Outlook.Application","");
ns = myolApp.GetNamespace("MAPI");
ns.Logon("", "", false, true);
Inbox = ns.Folders["Mailbox - Name"].Folders["Inbox"];
i = 0;
j = 1;
//Scan for attachments
foreach (object Item_loopVariable in Inbox.Items)
{
Item = Item_loopVariable;
System.Windows.Forms.Application.DoEvents();
if ((Item as MailItem) != null ? ((MailItem)Item).UnRead : false)
{
Body = ((Microsoft.Office.Interop.Outlook.MailItem)Item).Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).HTMLBody = Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).SaveAs(#"\\path\"+"filename", Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML );
j = j + 1;
}
}
//Clear Memory
Atmt = null;
Item = null;
ns = null;
}
catch (System.Exception ex)
{
MessageBox.Show("An unexpected error has occurred."
+ "\r\n" + "Please note and report the following information."
+ "\r\n" + "Script Name: GetAttachments"
+ "\r\n" + "Error Description: " + ex.Message
+ "\r\n" + "Error StackTrace: " + ex.StackTrace
, "Error!");
Atmt = null;
Item = null;
ns = null;
}
}
I need changes in these piece of code:
Body = ((Microsoft.Office.Interop.Outlook.MailItem)Item).Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).HTMLBody = Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).SaveAs(#"\\path\"+"filename", Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML );
Outlook has some issues with saving the body of an email, as far as the filesystem security goes. A workaround is to use the file system objects to save the body - worked for me.