Trouble with attaching gridview to email in DotNetNuke - c#

I was looking around and found this. It is quite similar to what I want to accomplish the only problem is that when I run the script nothing happens unless I remove the { attachment } line. However, if I remove that line I do not get my attachment.
private void SendEmail()
{
StringBuilder message;
Attachment attachment;
string strOrderType;
if (lblRequestType.Text == "Order Request")
{
strOrderType = "Order Request";
}
else
{
strOrderType = "Return Request";
}
string strName = txtFname.Text + " " + txtLname.Text;
string strOrderNum = lblOrderNum.Text;
string strSubject = "Request:" + strOrderNum + " - " + strName + " " + strOrderType;
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = sdsOrders;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.HeaderRow.Style.Add("background-color", "#003c74");
gridView.HeaderRow.Style.Add("color", "#ffffff");
for (int i = 0; i < gridView.Rows.Count; i++)
{
GridViewRow row = gridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.BackColor = System.Drawing.Color.AliceBlue;
}
}
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
System.Text.Encoding theEncoding = System.Text.Encoding.ASCII;
byte[] theByteArray = theEncoding.GetBytes(writer.ToString());
MemoryStream theMemoryStream = new MemoryStream(theByteArray, false);
//Visitor Message
if (txtEmail.Text.Length > 0)
{
message = new StringBuilder();
message.AppendLine("<h4 style=\"font-family: verdana, arial;\">Company Name</h4>");
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">Dear " + txtFname.Text + ",</p>");
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">Company Message.</p>");
message.AppendLine("Your Confirmation number is: " + strOrderNum);
attachment = new Attachment(theMemoryStream, strSubject);
Mail.SendMail("Address1#none.net", txtEmail.Text, "", "Address1#none.net",
"Address1#none.net", MailPriority.Normal, "Company Message", MailFormat.Html, Encoding.UTF8, message.ToString(),
new List<Attachment>() { attachment }, null, null, null, null, Host.EnableSMTPSSL);
}
//Internal Message
message = new StringBuilder();
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">YAY it worked.</p>");
// need to create new reference to attachment, cannot use same reference to send email twice
attachment = new Attachment(theMemoryStream, strSubject);
Mail.SendMail("Address1#none.net", "Address1#none.net", "", "Address1#none.net",
"", MailPriority.Normal, strSubject, MailFormat.Html, Encoding.UTF8, message.ToString(),
new List<Attachment>() { attachment }, null, null, null, null, Host.EnableSMTPSSL);
}
Please tell me where I am going wrong here

Related

Sending emails with a PDF attachment (C#)

I have an intranet site to manage clients' communications. There are only a few controls: a textbox for the Subject, Attachment (fileUpload control), and a multiline textbox for the content of the email.
Using the fileUpload control, I select the pdf file that I want to send to clients. All the details about the clients (name, email address, etc) is coming from a sql table.
The sending works just fine, it sends the email with the attachment. However, the PDF attachment cannot be opened. The error is that the file hasn't been correctly decoded. I am not sure where the problem is. Does anyone have an idea on where the problem is?
Here is the code (for the sending procedure):
protected void BtnSendAcctClientsEmail_Click(object sender, EventArgs e)
{
if (uplAcctngAttachment.HasFile)
{
HttpPostedFile uploadedFile = uplAcctngAttachment.PostedFile;
if (IsAcctngFileHeaderValid(uploadedFile))
{
var fileName = Path.GetFileName(uplAcctngAttachment.PostedFile.FileName);
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".pdf")
{
lblAcctngFileErr.Text = "Please attach pdf files only.";
return;
}
else
{
lblAcctngFileErr.Text = "";
}
try
{
DataSet ds_Emails = new DataSet();
constr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cn = new SqlConnection(constr);
cmd = new SqlCommand("getAcctClientsEmailAddresses", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da_Emails = new SqlDataAdapter(cmd);
cn.Open();
da_Emails.Fill(ds_Emails);
cn.Close();
for (int vLoop = 0; vLoop < ds_Emails.Tables[0].Rows.Count; vLoop++)
{
string name_first = ds_Emails.Tables[0].Rows[vLoop]["contact_fname"].ToString();
email = ds_Emails.Tables[0].Rows[vLoop]["email"].ToString();
client_id = ds_Emails.Tables[0].Rows[vLoop]["id"].ToString();
clientType = "acctng";
// Build the Body of the message using name_first into a string and then send mail.
//send e-mail
string fromAddress = "associates#example.com";
string ccAddress = fromAddress;
string subject = txtAcctngSubject.Text;
string sendEmail = "Dear " + name_first + "," + Environment.NewLine + Environment.NewLine + txtAcctngMessage.Text;
sendEmail += Environment.NewLine + Environment.NewLine + "Go to https://www.example.com/crm_removal.aspx?id=" + client_id +
"&type=" + clientType + " to be removed from any future communications.";
MailAddress fromAdd = new MailAddress(fromAddress, "Associates");
MailAddress toAdd = new MailAddress(email);
MailMessage eMailmsg = new MailMessage(fromAdd, toAdd);
Attachment attachment;
attachment = new Attachment(uplAcctngAttachment.PostedFile.InputStream, fileName);
eMailmsg.Subject = subject;
eMailmsg.Attachments.Add(attachment);
eMailmsg.Body = sendEmail;
SmtpClient client = new SmtpClient();
client.Send(eMailmsg);
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
sendingErr = ex.Message;
SendErr();
}
Response.Redirect("default.aspx", false);
}
}
}
private bool IsAcctngFileHeaderValid(HttpPostedFile uploadedFile)
{
Stream s = uplAcctngAttachment.PostedFile.InputStream;
StringBuilder buffer = new StringBuilder();
int value;
for (int i = 0; i < 2; i++)
{
value = s.ReadByte();
if (value == -1)
{
throw new Exception("Invalid file data.");
}
buffer.Append(value.ToString());
}
/*extension code list for files
* 7780 = exe
* 8075 = docx
* 3780 = pdf
* 7173 = gif
* 255216 = jpg
* 13780 = png
* 6677 = bmp
* 208207 =xls, doc, ppt
* 8075 = xlsx,zip,pptx,mmap,zip
* 8297 = rar
* 01 = accdb,mdb
*/
string[] input = { "208207", "8075", "3780", "255216", "13780", "6677" };
List<string> headers = new List<string>(input);
return headers.Contains(buffer.ToString());
}
When you pass the stream to the Attachment constructor it's offset by 2 bytes because you read from it earlier in IsAcctngFileHeaderValid corrupting the data.
Reset the stream position using uplAcctngAttachment.PostedFile.InputStream.Position = 0; when IsAcctngFileHeaderValid is done reading.

How to apped in table format using String builder

I am trying to make a table format in the body of email.
This is how I do the appending
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<table border='1' cellpadding='0' cellspacing='0'>");
sb.Append("<tr>");
sb.Append("<td>ID</td>");
sb.Append("<td>STATUS</td>");
sb.Append("</tr>");
//sb.Append("</table>");
//sb.Append(" < table border = '1' cellpadding = '0' cellspacing = '0' width = '100%' >");
foreach (var item in mylist)
{
sb.Append("<tr>");
sb.Append("<td>" + item.message + "</td>");
sb.Append("<td>" + item.transactionid + "</td>");
sb.Append("</tr>");
}
sb.Append("</table>");
var sendmail = new MailAddress("", "Akhil");
var receiver = new MailAddress("", "Buddy");
var subject = "Request for Asset!!";
var body = sb.ToString();
If you using System.Web.Mail then put messageg.BodyFormat = MailFormat.Html;
If you using System.Net.Mail then put message.IsBodyHtml = true; .
IsBodyHtml & MailFormat.Html states that your message is HTML formatted.
> This is not a true way, first you should add the HTML file, then after create a table inside the file.
Now attach a file with StringBuilder.
## Here is my send email with attachment code ##
StringBuilder sbMailBody = new StringBuilder();
sbMailBody.Append(Server.MapPath("~/Content/fielname.html"));
var sendmail = new MailAddress("", "Akhil");
var receiver = new MailAddress("", "Buddy");
var subject = "Request for Asset!!";
var body = sbMailBody.ToString();

Sending datagridview as mail with header

This is my code to send datagridview as email. This code works for me by just sending the data in the datagridview.
Please guide me how to add the table header in it. I want the email to be sent as whole table including the table header.
var client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("from_mail", "password");
var mail = new MailMessage();
mail.From = new MailAddress("from_mail");
mail.To.Add("to_mail");
mail.IsBodyHtml = true;
mail.Subject = "test";
string mailBody = "<table width='100%' style='border:Solid 1px Black;'>";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
mailBody += "<tr>";
foreach (DataGridViewCell cell in row.Cells)
{
mailBody += "<td>" + cell.Value + "</td>";
}
mailBody += "</tr>";
}
mailBody += "</table>";
//your rest of the original code
mail.Body = mailBody;
client.Send(mail);
MessageBox.Show("mail send");
this.Close();
For converting your DataGridView to HTML for sending it in an email, use the function below:
private StringBuilder DataGridtoHTML(DataGridView dg)
{
StringBuilder strB = new StringBuilder();
//create html & table
strB.AppendLine("<html><body><center><" +
"table border='1' cellpadding='0' cellspacing='0'>");
strB.AppendLine("<tr>");
//create table header
for (int i = 0; i < dg.Columns.Count; i++)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dg.Columns[i].HeaderText + "</td>");
}
//Close the header row
strB.AppendLine("</tr>");
//create table body
for (int i = 0; i < dg.Rows.Count; i++)
{
strB.AppendLine("<tr>");
foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dgvc.Value.ToString() + "</td>");
}
strB.AppendLine("</tr>");
}
//table footer & end of html file
strB.AppendLine("</table></center></body></html>");
return strB;
}

C# + Append DataTable row to html email template

I have a DataTable of records which I need to append as information to my Email template htm. Currently what I am doing here works fine but that is if I only have 1 row of record. How can I go about appending the htm template such that I can have multiple postings in the email
e.g Sample Email Screen (Assuming my DataTable returns 3 rows of record):
Dear Sir, your daily car posting results:
Image
Toyota
Cambry
$10000
Image
Honda
GT
$10000
Image
Nissan
Sunny
$10000
Loop DataTable row:
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
primaryImage = dr["PrimaryImage"].ToString();
email = dr["Email"].ToString();
postTitle = dr["Model"].ToString();
model = dr["Model"].ToString();
askingPrice = dr["AskingPrice"].ToString();
var mail = new Email();
mail.IsBodyHtml = true;
mail.MailAddresses = email;
mail.MailSubject = "Test";
mail.HtmFileName = "Email.htm";
var dict = new Dictionary<string, string>
{
{"<%PrimaryImage%>", primaryImage },
{"<%PostTitle%>", postTitle},
{"<%Model%>", model},
{"<%AskingPrice%", askingPrice}
};
mail.Dict = dict;
MailMessage mailMessage;
mailMessage = mail.CreateMailMessage();
Email.Send(mailMessage, 3, 3000, true);
}
}
Create Mail Message:
public MailMessage CreateMailMessage()
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = IsBodyHtml;
mail.From = new MailAddress("xxx#yahoo.com", "xxx");
mail.Bcc.Add(MailAddresses);
mail.Subject = MailSubject;
string body = "";
string filePath =
HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["TEMPLATES"] + "/");
if (File.Exists(filePath + HtmFileName))
{
FileStream f = new FileStream(filePath + HtmFileName, FileMode.Open);
StreamReader sr = new StreamReader(f);
body = sr.ReadToEnd();
foreach (var pair in Dict)
{
body = body.Replace(pair.Key, pair.Value);
}
f.Close();
}
mail.Body = body;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess |
DeliveryNotificationOptions.OnFailure;
return mail;
}
Portion of the Email.htm template:
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<div>
<a><img src="<%PrimaryImage%>"/></a>
<br/><br/>
Sell Post Title: <%PostTitle%>
<br/><br/>
Model: <%Model%>
<br/><br/>
Asking Price: <%AskingPrice%>
</div>
</form>
</body>
#M.S : There must be some condition on the basis of which you will decide which attribute goes to which td. You can wrap up this logic in some method and generate a class name. Below is a way how you generate a classname on the basis of rownum.
var className="" ;
var rowNum=0;
foreach (var entry in dataTable)
{
className=GetClassName(rowNum)
innerHtml += "<tr>";
innerHtml += "<td class='"+ className +"'>" + entry.PrimaryImage + "</td> ";
innerHtml += "</tr>";
rowNum++;
}
public static string GetClassName(int rowCount)
{
switch (rowCount)
{
case 1:
return "class1";
case 2:
return "class2";
case 3:
return "class3";
default:
return "unassignedClass";
}
}
I have always used HtmlAgilityPack to prepare htmlcontent and achieve things like this.
private string PrepareHtmlContent(List<DataRow> dataTable)
{
var htmlDocument = new HtmlDocument();
var html = EmailTemplates.GetTemplate("yourTemplate");
htmlDocument.LoadHtml(html);
var recordsContainerNode = htmlDocument.GetElementbyId("dataTable");
if (recordsContainerNode != null)
{
var innerHtml = "";
foreach (var entry in dataTable)
{
innerHtml += "<tr>";
innerHtml += "<td>" + entry.PrimaryImage + "</td> ";
innerHtml += "<td>" + entry.Model + "</td> ";
innerHtml += "<td>" + entry.AskingPrice + "</td> ";
innerHtml += "</tr>";
}
recordsContainerNode.InnerHtml = innerHtml;
}
using (var stringWriter = new StringWriter())
{
htmlDocument.Save(stringWriter);
return stringWriter.GetStringBuilder().ToString();
}
}
And your template should be sth like this
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<table>
<thead> </thead>
<tbody id="dataTable">
</tbody>
</table>
</form>
</body>

Retrieving mails from a remote Exchange Server. Some sort of security issue

This code works on my local with Exchange hosted a VM, but not when trying to recieve mails from the clients Exchange server.
The point is to check a mailbox, extract details, start a workflow and attach email and any other attachments in the email, and move the email from the Inbox folder to my custom folder 'Saved'. This all works on my local machine.
These are the errors I get:
The request failed. The underlying connection was closed: An unexpected error occurred on a send.
Inner Exception: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
My code breaks at this point:
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, view);
Please excuse any other shitty code, its not production ready and this is a shortened version I edited so items may be missing.
Here is the rest of the code. (I have a separate class that does the Authentication and holds all the credentials for mailboxes. I have listed that first)
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
public static ExchangeService ConnectToService(IUserData userData)
{
return ConnectToService(userData,null);
}
public static ExchangeService ConnectToService(IUserData userData, ITraceListener listener)
{
ExchangeService service = new ExchangeService(userData.Version);
if (listener != null)
{
service.TraceListener = listener;
service.TraceFlags = TraceFlags.All;
service.TraceEnabled = true;
}
service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);
if (userData.AutodiscoverUrl == null)
{
Uri myUri = new Uri("https://IPAddress/ews/exchange.asmx");
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUri);
var test = webRequest.RequestUri;
webRequest.Proxy.IsBypassed(test);
webRequest.ClientCertificates.Clear();
webRequest.KeepAlive = false;
service.KeepAlive = false;
//NEW ****** ATTEMPTED FIXES
webRequest.Accept = "*/*";
service.AcceptGzipEncoding = true;
webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
var version = service.RequestedServerVersion;
userData.Version.Equals(ExchangeVersion.Exchange2013);
userData.AutodiscoverUrl = myUri;
service.Url = myUri;
}
else
{
service.Url = userData.AutodiscoverUrl;
}
return service;
}
public static ExchangeService ConnectToServiceWithImpersonation(
IUserData userData,
string impersonatedUserSMTPAddress)
{
return ConnectToServiceWithImpersonation(userData, impersonatedUserSMTPAddress, null);
}
public static ExchangeService ConnectToServiceWithImpersonation(
IUserData userData,
string impersonatedUserSMTPAddress,
ITraceListener listener)
{
ExchangeService service = new ExchangeService(userData.Version);
if (listener != null)
{
service.TraceListener = listener;
service.TraceFlags = TraceFlags.All;
service.TraceEnabled = true;
}
service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);
ImpersonatedUserId impersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserSMTPAddress);
service.ImpersonatedUserId = impersonatedUserId;
if (userData.AutodiscoverUrl == null)
{
service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback);
userData.AutodiscoverUrl = service.Url;
}
else
{
service.Url = userData.AutodiscoverUrl;
}
return service;
}
THIS IS WHERE THE FUNCTIONALITY HAPPENS, AND CODE BREAKS # FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, view);
static void RecieveMails(ExchangeService service)
{
string SitePath = #"C:\temp\";
int numOfFiles = 0;
int numOfAttachments = 0;
int fileCount = 0;
int filePosition = -1;
string pickupPath = Path.Combine(SitePath);
string uniqueRefNo;
Random memberNo = new Random();
string memberNumber = memberNo.Next().ToString();
ClientCredentials cc = new ClientCredentials();
var username = cc.UserName.ToString();
var service2 = new Microsoft.Exchange.WebServices.Data.ExchangeService();
var sVersion = service2.RequestedServerVersion;
var testVersion = service.RequestedServerVersion;
// Create a view with a page size of 10.
ItemView view = new ItemView(1);
// Indicate that the base property will be the item identifier
view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
view.PropertySet.Add(ItemSchema.IsAssociated);
// Set the traversal to associated. (Shallow is the default option; other options are Associated and SoftDeleted.)
view.Traversal = ItemTraversal.Associated;
//////Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
service.HttpHeaders.Values.DefaultIfEmpty("*/*");
service.HttpResponseHeaders.Add("Accept", "*/*");
service.KeepAlive = false;
service2.KeepAlive = false;
** /////** BREAKS HERE AT FindItems** /////**
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, view);
findResults = service.FindItems(
WellKnownFolderName.Inbox,
new ItemView(1)); //# is the number of mails to fetch
foreach (Item item in findResults.Items)
{
//this needs to be here to recieve the message body
MessageBody messageBody = new Microsoft.Exchange.WebServices.Data.MessageBody();
List<Item> items = new List<Item>();
if (findResults.Items.Count > 0) // Prevent the exception
{
foreach (Item item2 in findResults)
{
items.Add(item2);
}
}
service.LoadPropertiesForItems(items, PropertySet.FirstClassProperties);
messageBody = item.Body.ToString().Replace("<html dir=", "").Replace("<head>", "").Replace("<meta http-equiv=", "").Replace("content=", "")
.Replace("<style type=", "").Replace("</style>", "").Replace("</head>", "").Replace("<body fpstyle=", "").Replace("ocsi=", "")
.Replace("<div style=", "").Replace("direction: ltr;font-family: Tahoma;color: #000000;font-size: 10pt;", "").Replace("</div>", "")
.Replace("<div>", "").Replace("</body>", "").Replace("</html>", "").Replace("<br>", "").Replace(">", "").Replace("\"Content-Type", "")
.Replace("\"text/html; charset=utf-8", "").Replace("\"0", "").Replace("\"", "").Replace("text/css", "")
.Replace("id=owaParaStyle", "").Replace("ltr", "").Replace("<meta name=GENERATOR MSHTML 9.00.8112.16470", "").Replace("<style P {", "")
.Replace("MARGIN-TOP: 0px; MARGIN-BOTTOM: 0px", "").Replace("<p", "").Replace("</p>", "").Replace("</p", "").Replace(" ", "")
.Replace("<body fPStyle= ", "").Replace("%", "").Replace("<", "").Replace(">", "").Replace("}", "").Replace("\"","").Replace("body fPStyle=1","");//.Replace("\"1", "")
//messageBody = Regex.Replace(messageBody, #"(?:\r\n|\r(?!\n)|(?!<\r)\n){2,}", "");
string subject = item.Subject.ToString();
//Write results to Console
Console.WriteLine("==========================================================================");
Console.WriteLine("To: " + item.DisplayTo);
Console.WriteLine("Subject: " + subject);
Console.WriteLine("Message Body: " + messageBody);
Console.WriteLine();
Console.WriteLine("Date & Time Received: " + item.DateTimeReceived);
Console.WriteLine("HasAttachments: " + item.HasAttachments);
Console.WriteLine();
//saving email content to local drive
string fileDateTime = item.DateTimeReceived.ToString();
fileDateTime = fileDateTime.Replace("/", "-").Replace(":", "-");
string newFileName = "Email " + fileDateTime + " - " + "E_Subject- " + item.Subject.Replace(":", "").Replace("*", "").Replace(".", "").Replace(",", "")
.Replace(";", "").Replace("?", "").Replace("<p", "").Replace("</p>", "").Replace("</p", "")
.Replace("<meta name=GENERATOR MSHTML 9.00.8112.16470", "").Replace("<style P {", "").Replace("MARGIN-TOP: 0px; MARGIN-BOTTOM: 0px", "")
.Replace("}", "").Replace("/", "").Replace("&", "").Replace("#", "").Replace("#", "").Replace("!", "")
.Replace("%", "").Replace("<", "").Replace(">", "").Replace(" ", "").Replace("<body fPStyle= ", "");
string mydocpath = SitePath + newFileName + ".txt";
string From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)item[EmailMessageSchema.From]).Address;
string WFType = subject;
string DocumentType = "From Email";
int WFTypeID = PPS.SM.Services.WorkflowDataService.GetWFTypeID(WFType);
StringBuilder sb = new StringBuilder();
//Text file content
sb.AppendLine("Sent From: " + From);
sb.AppendLine("Sent To: " + item.DisplayTo);
sb.AppendLine("Email Subject: " + subject);
sb.AppendLine("Date and time received: " + item.DateTimeReceived.ToString());
sb.AppendLine("CC: " + item.DisplayCc);
sb.AppendLine("Number of Attachments: " + item.Attachments.Count.ToString());
sb.AppendLine();
sb.AppendLine("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
sb.AppendLine();
sb.Append("Email message body: " + messageBody);
sb.AppendLine();
using (StreamWriter outfile = new StreamWriter(mydocpath, true))
{
outfile.WriteLine(sb.ToString());
}
//Save attachments to local drive
int attCount = item.Attachments.Count();
foreach (Attachment attachment in item.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load();
Console.WriteLine("Attachment name: " + fileAttachment.Name);
string attname = newFileName.Replace("Email ", "");
//File location
fileAttachment.Load(SitePath + "Attachment " + attname + " -Att_Fname- " + fileAttachment.Name); // Stream attachment contents into a file.
}
else// Attachment is an item attachment.
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load();
string attname = newFileName.Replace("Email ", "");
Console.WriteLine("Attachment " + attname + itemAttachment.Name);
}
}
PPS.SM.IAASMAgent.SMAgent client = new PPS.SM.IAASMAgent.SMAgent();
var result = client.CreateWorkflow(WFTypeID, "iaasystem", "$1Elvis", "iquitowitz", "", "", "EmailService", "FromEmail", "", "", "", "", memberNumber, "South Africa", "FGV256", "", "", "", "", "", "", 0, "", "", "", false, false, "", "", "", 0, "", false, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", decimal.Parse("0"), false, false, true).ToString();
Console.WriteLine(result);
string WFnum = result.Substring(result.IndexOf('>', result.LastIndexOf("<Workflownumber>")) + 1);
WFnum = WFnum.Split('<')[0];
int WFnumber = int.Parse(WFnum.ToString());
string IDNumber = result.Substring(result.IndexOf('>', result.LastIndexOf("<IDNumber>")) + 1);
IDNumber = IDNumber.Split('<')[0];
foreach (string file in Directory.GetFiles(pickupPath, "*"))
{
bool contains = false;
if (contains = Regex.Match(file.ToString(), item.DateTimeReceived.ToString().Replace("/", "-").Replace(":", "-"), RegexOptions.IgnoreCase).Success)
{
fileCount++;
}
}
var WFattachment = new string[fileCount];
ConfigurationManager.RefreshSection("applicationSettings");
string sp = ConfigurationManager.AppSettings["UploadToSharePoint"];
string dc = ConfigurationManager.AppSettings["UploadToDocumentum"];
Console.WriteLine(ConfigurationManager.AppSettings["UploadToSharePoint"]);
Console.WriteLine(ConfigurationManager.AppSettings["UploadToDocumentum"]);
AgentServiceClient asc = new AgentServiceClient();
//Upload to Sharepoint
if (sp == "True")
{
PPS.SM.DocumentumAgentService.AgentServiceClient client2 = new PPS.SM.DocumentumAgentService.AgentServiceClient();
if (Directory.Exists(pickupPath))
{
foreach (string file in Directory.GetFiles(pickupPath, "*"))
{
bool contains = false;
if (contains = Regex.Match(file.ToString(), item.DateTimeReceived.ToString().Replace("/", "-").Replace(":", "-"), RegexOptions.IgnoreCase).Success)
{
filePosition++;
Console.WriteLine("Regex match: " + contains.ToString());
numOfFiles++;
if ((contains = Regex.Match(file.ToString(), "Email", RegexOptions.IgnoreCase).Success) && (contains != Regex.Match(file.ToString(), "Attachment", RegexOptions.IgnoreCase).Success))//this file is an email
{
WFattachment[filePosition] = file.ToString();
byte[] bytesfile = System.IO.File.ReadAllBytes(file.ToString());
uniqueRefNo = PPS.SM.Services.WorkflowDataService.GenerateDocRefNo();
string documentGroup = client2.GetDocumentGroup(DocumentType);
var createdDate = DateTime.Now.Date;
var contentType = new FileInfo(file).Extension;
client2.UploadFile("iquitowitz", WFnumber, bytesfile, file.ToString(), "South Africa", "FromEmail", memberNumber, "Test", WFType, documentGroup, "EmailService", IDNumber, "1900-01-01 00:00:00.000", 3, uniqueRefNo, "Sharepoint", int.Parse(memberNumber), "",contentType, createdDate);
//assoiciate as document to workflow
if (dc == "False")
{
File.Delete(file);
}
//}
}
else //this file is an attachment
{
//add file to WF
Console.WriteLine("Attachment file found on local drive # " + file.ToString());
Console.WriteLine("\n");
numOfAttachments++;
WFattachment[filePosition] = file.ToString();
byte[] bytesfile = System.IO.File.ReadAllBytes(file.ToString());
uniqueRefNo = PPS.SM.Services.WorkflowDataService.GenerateDocRefNo();
string documentGroup = client2.GetDocumentGroup(DocumentType);
var createdDate = DateTime.Now.Date;
var contentType = new FileInfo(file).Extension;
client2.UploadFile("ServiceManager", WFnumber, bytesfile, file.ToString(), "South Africa", "FromEmail", memberNumber, "Test", WFType, documentGroup, "EmailService", IDNumber, "1979-06-19 00:00:00.000", 3, uniqueRefNo, "Sharepoint", int.Parse(memberNumber), "", contentType, createdDate);
if (dc == "False")
{
File.Delete(file);
}
}
}
}
}
}
filePosition = -1;
//Upload to Documentum
if (dc == "True")
{
if (Directory.Exists(pickupPath))
{
foreach (string file in Directory.GetFiles(pickupPath, "*"))
{
bool contains = false;
if (contains = Regex.Match(file.ToString(), item.DateTimeReceived.ToString().Replace("/", "-").Replace(":", "-"), RegexOptions.IgnoreCase).Success)
{
filePosition++;
Console.WriteLine("Regex match: " + contains.ToString());
numOfFiles++;
if ((contains = Regex.Match(file.ToString(), "Email", RegexOptions.IgnoreCase).Success) && (contains != Regex.Match(file.ToString(), "Attachment", RegexOptions.IgnoreCase).Success)) //this file is an email
{
Console.WriteLine("\n");
WFattachment[filePosition] = file.ToString();
byte[] bytesfile = System.IO.File.ReadAllBytes(file.ToString());
var docresult = asc.UploadDocument("iquitowitz", "p", WFnumber, bytesfile, file.ToString().Replace(SitePath, ""), "South Africa", "FromEmail", memberNumber, "", WFType, "", IDNumber, "", 3);
Console.WriteLine(docresult);
//if success
File.Delete(file);
//}
}
else if (contains = Regex.Match(file.ToString(), "Attachment", RegexOptions.IgnoreCase).Success) //this file is an attachment
{
//add file to WF
Console.WriteLine("Attachment file found on local drive # " + file.ToString());
Console.WriteLine("\n");
//numOfAttachments++;
WFattachment[filePosition] = file.ToString();
byte[] bytesfile = System.IO.File.ReadAllBytes(file.ToString());
var docresult = asc.UploadDocument("ServiceManager", "p", WFnumber, bytesfile, file.ToString().Replace(SitePath, ""), "South Africa", "FromEmail", memberNumber, "", WFType, "", IDNumber, "", 3);
Console.WriteLine(docresult);
//if success
File.Delete(file);
}
}
}
}
}
Console.WriteLine("Number of attachment files found on local drive: " + numOfAttachments.ToString());
if (fileCount != 0)
for (int i = 0; i < fileCount; )
{
Console.WriteLine("Attachment Location: " + WFattachment[i]);
i++;
if (i != fileCount)
{
Console.WriteLine("");
}
}
//if (WorkflowWasCreated) then move email to saved folder
//here I move the mail to my custom folder "Saved"
Folder rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot);
rootfolder.Load();
foreach (Folder folder in rootfolder.FindFolders(new FolderView(100)))
{
// This IF limits what folder the program will seek
if (folder.DisplayName == "Saved")
{
var fid = folder.Id;
//Console.WriteLine(fid);
item.Load();
//item.Subject = (fileDateTime) +" - " + subject.ToString();
item.Update(ConflictResolutionMode.AlwaysOverwrite);
item.Move(fid);
Console.WriteLine("\n");
Console.WriteLine("Email moved from Inbox to: '" + folder.DisplayName + "' folder as '" + item.Subject + "'");
}
}
}
}
I found the issue, which was a mission as I had to get extra information from a Server Engineer at the client. After trying a bunch os scenarios we found the issue. The problem was here:
Uri myUri = new Uri("https://IPAddress/ews/exchange.asmx");
where I was using the Exchange servers's IP address. Instead I have to go via webmail and the company domian
Uri myUri = new Uri("https://webmail.CompanyDomain.com/ews/exchange.asmx");
and then this service worked. Hope this can help anyone who comes along an issue like this.

Categories

Resources