I have a custom add-in which gets the body on clicking a button when it got installed. so I am getting this error on a customer machine. code is working fine on my side and for other customers but one customer is facing this problem.
this is my code
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Explorer olExp = olApp.ActiveExplorer();
Selection olSel = olExp.Selection;
string msg = "";
int iterate = 1;
MAPIFolder inbox = null;
if (olSel.Count > 1)
{
MessageBox.Show("Sorry! You can't report more then 1 email at a time", "Report Email");
return;
}
foreach (_MailItem mail in olSel)
{
inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mail.GetInspector.Display(false);
Thread.Sleep(2100);
string screenShot = getScreenShot(mail);
mail.GetInspector.Close(OlInspectorClose.olDiscard);
String msgToShow = "Are you sure you want to report this email as suspicious?";
if (mail != null && mail.Subject != null)
msgToShow += "\n\nSubject : " + mail.Subject.ToString();
DialogResult dr = MessageBox.Show(msgToShow, "Please Confirm", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
msg += reportMail(mail, screenShot, e);
}
else {
return;
}
iterate++;
break;
}
if (!msg.Equals(""))
MessageBox.Show(msg, "Report Email");
else
return;
if (!msg.Contains("Success"))
return;
MailItem moveMail = null;
MAPIFolder subfolder = null;
try
{
subfolder = inbox.Folders["Reported Emails"];
}
catch (System.Exception ex) {
subfolder = inbox.Folders.Add("Reported Emails", OlDefaultFolders.olFolderInbox);
}
foreach (MailItem eMail in olSel)
{
try
{
moveMail = eMail;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
moveMail.Move(subfolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private string reportMail(_MailItem mail, string screenShot, RibbonControlEventArgs e)
{
try
{
var m = Globals.ThisAddIn.Application.GetNamespace("MAPI");
var mailitem = mail;
if (mailitem != null)
{
// Console.WriteLine("Email body ::: " + mailitem.HTMLBody);
String reporterEmail = getReporterEmail(mailitem);
String senderEmailAddress = "";
String senderName = "";
AddressEntry mailsender;
if (reporterEmail.Equals(""))
{
MessageBox.Show("Sorry! This email can't be reported because you are not included in Recipients.", "Report Email");
}
else
{
if (mailitem.SenderEmailType == "EX")
{
mailsender = mailitem.Sender;
if (mailsender != null)
{
if (mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
ExchangeUser exchUser = mailsender.GetExchangeUser();
if (exchUser != null)
{
senderEmailAddress = exchUser.PrimarySmtpAddress;
senderName = exchUser.Name;
}
}
}
}
else
{
senderEmailAddress = mailitem.SenderEmailAddress;
senderName = mailitem.SenderName;
}
String emailHeader = mailitem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
String emailBody = mailitem.Body.Replace("%"," percent").Replace("#","").Replace("|", "");
//String res = HttpPost(Properties.Settings.Default.address, "ReporterEmail=" + reporterEmail + "&suspectedName=" + senderName + "&FromEmail=" + senderEmailAddress
// + "&ToEmail=" + mailitem.To + "&Subject=" + mailitem.Subject + "&EmailBody=" + emailBody + "&AttachmentName=" + GetAttachments(mailitem)
// + "&reporter=" + reporterEmail + "&emailHeader=" + emailHeader + "&mailImage=" + screenShot);
String htmlBody = mail.HTMLBody;
MessageBox.Show(htmlBody);
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("ReporterEmail", reporterEmail);
postParameters.Add("suspectedName", senderName);
postParameters.Add("FromEmail", senderEmailAddress);
postParameters.Add("ToEmail", mailitem.To);
postParameters.Add("Subject", mailitem.Subject);
postParameters.Add("EmailBody", emailBody);
List<String> attachmentDetails = GetAttachments(mailitem);
postParameters.Add("AttachmentName", attachmentDetails[0]);
postParameters.Add("reporter", reporterEmail);
postParameters.Add("emailHeader", emailHeader);
postParameters.Add("mailImage", screenShot);
string res = HttpPost(Properties.Settings.Default.serverAddress+ "/PhishRod-portlet/reporter", postParameters, htmlBody,attachmentDetails[1]);
return res + "\n";
}
}
}
catch (System.Exception ex)
{
log.Error(ex);
return "Error: " + ex + "-- - " + ex.StackTrace.ToString() + "\n";
}
return "";
}
In the event handler of your button I see the following lines of code:
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
There is no need to create a new Outlook Application instance in the add-in. Instead, you need to use the Application property which doesn't trigger a security issue when dealing with OOM from external applications:
var app = Globals.ThisAddIn.Application
Related
I am continuously getting this error failure sending mail. I have already tried by changing port 465/25/587 but nothing worked. My credentials are also correct. All these configurations are for outlook. Checked all the ports they are also not blocked. The same code was working fine before but from last couple of days getting this error. Unable to get what's happening in this code.
Below is my code-
protected void btnSubmitClick(object sender, EventArgs e)
{
try
{
if (ddlSubCategory.SelectedIndex > 0)
{
if (Session["sessionID"] != null && Session["sessionID"].ToString().ToUpper().Trim() == "SUBMITTED")
{
// string textForMessage = #"<script language='javascript'> alert('Request Already Submitted for the same...!');</script>";
// ClientScript.RegisterClientScriptBlock(this.GetType(), "Stop", textForMessage); return;
}
if (fupAttachment.HasFile) { ViewState["file1"] = "0"; }
if (ViewState["file1"].ToString() == "0")
{
IssuesCommon issueCommon = new IssuesCommon();
issueCommon.IssueCateId = Convert.ToInt32(ddlSubCategory.SelectedValue);
issueCommon.Status = "OPEN";
issueCommon.LogBy = issueCommon.EmpId = Convert.ToInt32(getEmpDetail().Split('$')[0]);
issueCommon.Description = txtDesc.Text.Trim();
issueCommon.WorkStation = txtWorkStation.Text.Trim();
issueCommon.IPAddress = hfIP.Value;
issueCommon.Contact = txtphn.Text.Trim();
issueCommon.DepartmentId = Convert.ToInt32(Request.QueryString["help"]);
issueCommon.Supervisor = hfSuperId.Value;
string ticket = lblDeskName.Text + "#00" + Convert.ToString(Convert.ToInt32(objBal.getMaxIssueID()) + 1);
issueCommon.TicketNo = ticket;
issueCommon.Priority = (ddlPriority.SelectedValue == "Low" ? ddlSubPriority.SelectedValue : ddlPriority.SelectedValue);
issueCommon.attachmentName = fupAttachment.HasFile ? Server.MapPath("~/image/") + fupAttachment.FileName : null;
if (trSelectClient.Visible == true)
{
issueCommon.clientName = ddlClientList.SelectedValue.ToString() == "--Select--" ? "" : ddlClientList.SelectedValue.ToString();
}
else
{
issueCommon.clientName = "";
}
objBal.InsertIssue(issueCommon);
#region Mail Section
MailMessage mM = new MailMessage();
mM.From = new MailAddress("no-reply#xxxxxxx.com");
mM.To.Add(getDapartmentEmailId());
if (txtAddRecipient.Text != "" && txtAddRecipient.Text != null && trAddRecipient.Visible == true)
{
mM.CC.Add(txtAddRecipient.Text);
}
if (Session["help"] != null)
{
if (Convert.ToString(Session["help"]) == "1")
{
mM.Bcc.Add("abc#xxxxxx.com");
}
}
if (fupAttachment.HasFile)
{
string filename = fupAttachment.FileName;
fupAttachment.SaveAs(Server.MapPath("~/images/") + filename);
Attachment attach = new Attachment(Server.MapPath("~/images/") + filename);
mM.Attachments.Add(attach);
}
mM.Subject = "Issue Ticket#: " + issueCommon.TicketNo + " [Priority: " + issueCommon.Priority + "]";
string mailBody = "Hello," +
"<br/> I am having the below issue: <br/><br> Issue Category : " + ddlSubCategory.SelectedItem.Text
+ " <br/> <br/> Workstation: " + txtWorkStation.Text + " <br/><br/> IP Address : " + txtIP.Text
+ "<br /><br /> Client Name: " + ddlClientList.SelectedValue.ToString().Replace("--Select--", "N/A")
+ "<br /><br /> My ContactNo: " + txtphn.Text
+ "<br/><br/> Description : " + txtDesc.Text.Trim() + "<br/><br/> Thanks, <br/>" + hfEmpid.Value + "/" + username.Text;
mM.Body = mailBody;
mM.IsBodyHtml = true;
mM.Priority = MailPriority.High;
SmtpClient sC = new SmtpClient("smtp.office365.com");
sC.Port = 587;
sC.EnableSsl = true;
sC.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sC.Credentials = new NetworkCredential("email", "password");
sC.Send(mM);
SendMailtoUser(issueCommon.TicketNo, lblUserName.Text.Trim());
Session["sessionID"] = "Submitted"; ViewState["file1"] = "0"; clearView();
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Your request has been submitted successfully');", true);
#endregion
}
else
{
string textForMessage = #"<script language='javascript'> alert('Select Attachment ');</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "UserPopup", textForMessage);
}
}
else { Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Select Issue Category');", true); }
}
catch (Exception ex) {
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('" + ex.Message.Replace("'", "") + "');", true); }
}
Please see the exception screenshot here
enter image description here
if you try this i think sending mail will be successful
var smtpClient = new SmtpClient(hostname, 25);
// userNameShort = "ab", domain = "outlook" for example
var networkCredential = new NetworkCredential(userNameShort, password, domain);
smtpClient.Credentials = networkCredential;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtpClient.EnableSsl = true;
smtpClient.Send(message);
Please can you trying:
SmtpClient sC = new SmtpClient("smtp.office365.com");
after adding
sC.Credentials = new NetworkCredential("email", "password");
then
sC.Port = 587;
//your codes
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 have an issue in LDAP with Asp.net IIS application.
I am just reading the user from Active directory, like below,
public class ActiveDirectoryRepository : IActiveDirectoryRepository
{
#region Public methods
List<User> IActiveDirectoryRepository.GetActiveDirectoryUsers(string loginName)
{
List<User> activeDirectoryUsersList = new List<User>();
try
{
string activeDirectory = System.Configuration.ConfigurationManager.AppSettings["EDPUserDomain"];
var searchRoot = new DirectoryEntry(activeDirectory);
var search = new DirectorySearcher(searchRoot);
FormUserSearchFilter(loginName, search);
SearchResultCollection activeDirectoryUsers = search.FindAll();
if (activeDirectoryUsers != null)
{
for (int counter = 0; counter < activeDirectoryUsers.Count; counter++)
{
string userNameEmailString = string.Empty;
SearchResult result = activeDirectoryUsers[counter];
if (result != null && result.Properties.Contains("displayname"))
{
User activeDirectoryUser = new User();
if (result.Properties["givenname"].Count > 0)
{
activeDirectoryUser.FirstName = Convert.ToString(result.Properties["givenname"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["sn"].Count > 0)
{
activeDirectoryUser.LastName = Convert.ToString(result.Properties["sn"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["mail"].Count > 0)
{
activeDirectoryUser.email = Convert.ToString(result.Properties["mail"][0], CultureInfo.InvariantCulture);
}
if (result.Properties["distinguishedname"].Count > 0)
{
string[] domain = Convert.ToString(result.Properties["distinguishedname"][0], CultureInfo.InvariantCulture).Split(',');
if (domain[2] != null)
{
activeDirectoryUser.DomainName = domain[2].Replace("DC=", String.Empty);
}
}
if (result.Properties["samaccountname"].Count > 0)
{
activeDirectoryUser.UserName = Convert.ToString(result.Properties["samaccountname"][0], CultureInfo.InvariantCulture);
}
activeDirectoryUsersList.Add(activeDirectoryUser);
}
}
}
}
catch (Exception ex)
{
string filePath = #"C:\Mails\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
return activeDirectoryUsersList;
}
The above code works well in debugging mode, but it throws the below error after deployed the application in IIS 6.1
Message :An operations error occurred.
<br/>
StackTrace : at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindAll()
at PW.EPD.DataAccess.Repository.ActiveDirectoryRepository.PW.EPD.DataAccess.Repository.IActiveDirectoryRepository.GetActiveDirectoryUsers(String loginName)
Date :5/20/2015 11:50:30 PM
-----------------------------------------------------------------------------
Please help me.
Thanks in advance.
public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
DataTable GetListID = new DataTable();
try
{
SqlParameter[] arParams = new SqlParameter[4];
arParams[0] = new SqlParameter("#Date", typeof(DateTime));
arParams[0].Value = objFeedRetPL.requestdate;
}
catch (Exception ex)
{
string dir = #"C:\Error.txt"; // folder location
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
File.AppendAllText(Server.MapPath("~/Error.txt"), New);
}
}
}
Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In
C drive Error.txt
Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:
string filePath = #"C:\Error.txt";
Exception ex = ...
using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
writer.WriteLine( "-----------------------------------------------------------------------------" );
writer.WriteLine( "Date : " + DateTime.Now.ToString() );
writer.WriteLine();
while( ex != null )
{
writer.WriteLine( ex.GetType().FullName );
writer.WriteLine( "Message : " + ex.Message );
writer.WriteLine( "StackTrace : " + ex.StackTrace );
ex = ex.InnerException;
}
}
The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErrorLoggingSample
{
class Program
{
static void Main(string[] args)
{
try
{
string str = string.Empty;
if (string.IsNullOrEmpty(str))
{
throw new Exception("Wrong Data");
}
}
catch (Exception ex)
{
ErrorLogging(ex);
ReadError();
}
}
public static void ErrorLogging(Exception ex)
{
string strPath = #"D:\Rekha\Log.txt";
if (!File.Exists(strPath))
{
File.Create(strPath).Dispose();
}
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error Logging ===========");
sw.WriteLine("===========Start============= " + DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
sw.WriteLine("===========End============= " + DateTime.Now);
}
}
public static void ReadError()
{
string strPath = #"D:\Rekha\Log.txt";
using (StreamReader sr = new StreamReader(strPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
I use that one
catch (Exception e)
{
new MessageWriteToFile(e).WriteToFile();
}
public class MessageWriteToFile
{
private const string Directory = "C:\\AppLogs";
public string Message { get; set; }
public Exception Exception { get; set; }
public string DefaultPath
{
get
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var folder = $"{Directory}\\{appName}";
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
return $"{Directory}\\{appName}\\{fileName}";
}
}
public MessageWriteToFile(string message)
{
Message = message;
}
public MessageWriteToFile(Exception ex)
{
Exception = ex;
}
public bool WriteToFile(string path = "")
{
if (string.IsNullOrEmpty(path))
{
path = DefaultPath;
}
try
{
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
writer.WriteLine();
if (Exception != null)
{
writer.WriteLine(Exception.GetType().FullName);
writer.WriteLine("Source : " + Exception.Source);
writer.WriteLine("Message : " + Exception.Message);
writer.WriteLine("StackTrace : " + Exception.StackTrace);
writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
}
if (!string.IsNullOrEmpty(Message))
{
writer.WriteLine(Message);
}
writer.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
}
Try This
try
{
int i = int.Parse("Prashant");
}
catch (Exception ex)
{
this.LogError(ex);
}
private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(message);
writer.Close();
}
}
string[] path1 = Directory.GetFiles(#"E:\storage", "*.txt");//it get the all textfiles from the folder
for (var i = 0; i < path1.Length; i++)
{
var file = Directory.GetDirectories(networkPath);
var path = file;
string temp_FilePath = "E:\\temp.txt";
string temp_FilePath1 = #"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
string temp_FilePath2 = #"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
string folder = #"E:\ExceptionFiles\Cs_regular";
string folder1 = #"E:\ExceptionFiles\CC_eBilling";
string[] lines;
var list = new List<string>();
var list1 = new List<string>();
var list2 = new List<string>();
var error = false;
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
var timenow1 = "2020/10/31 10:11";
if (res == timenow1)
{
string linesRemoved = "ERROR";
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list1.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if (line.Contains("Exception1") && error == false)
{
list1.Add(line);
error = true;
}
}
}
}
using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
{
string line;
while ((line = streamReader2.ReadLine()) != null)
{
string linesRemoved = "ERROR";
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
var timenow1 = "2020/10/29 12:38";
if (res == timenow1)
{
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list2.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
{
list2.Add(line);
error = true;
}
}
}
}
if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
{
int fileCount = Directory.GetFiles(folder).Length;
int fileCount1 = Directory.GetFiles(folder1).Length;
fileCount++;
fileCount1++;
temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";
}
{
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
System.IO.File.WriteAllLines(temp_FilePath, list);
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
}
}
catch (Exception ex)
{
}
return null;
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.