Downloading email attachment from MailBox using Pop3.dll in .net - c#

I am using vs 2010 for developing a winform application using c#.
For dowloading email attachments from mailbox i have used pop3.dll
my code download attachment when i use it on my machine which is direclty connected to internet but when i use it inside a domain where ISA server 2004 is used as a firewall my code only shows me how many message the mailbox box has and then goes for waiting
please can anybody tell me why and what should i do to resolve this problem..
here is the code
public bool DownloadEmailWithAttachment(string Type)
{
try
{
EventLog.WriteEntry("Service", "Attachment Path :> " + AttachmentDir);
long count = 0;
Pop3Client email = new Pop3Client(UserName, Password, IncomingPopAddress);
email.OpenInbox();
//LogEntry();
EventLog.WriteEntry("Service", "Counter :> " + email.MessageCount);
while (email.NextEmail())
{
count = email.MessageCount;
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)enumerator.Current;
string checkIfFile = multipart.Filename;
if (checkIfFile != null)
{
//Console.WriteLine("checkIfFile.Contains('Leave') =" + checkIfFile.ToString());
EventLog.WriteEntry("Service", "checkIfFile.Contains('"+Type+"') =" + checkIfFile.ToString());
if (checkIfFile.Contains(""+Type))
{
EventLog.WriteEntry("Service", "Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Encoding.ASCII.GetBytes(multipart.Data);
//Search FileName
int fileLength = checkIfFile.Length;
EventLog.WriteEntry("Service", "fileLength=" + fileLength);
//int Begin = multipart.ContentType.IndexOf("name="+checkIfFile.ToString());
string leFileNale = checkIfFile.ToString();
EventLog.WriteEntry("Service", leFileNale);
FileStream LeFS = new FileStream(AttachmentDir + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
string DeleteMailContainingSubject = email.Subject.ToString();
if (email.Subject.Contains(DeleteMailContainingSubject))
{
email.DeleteEmail();
EventLog.WriteEntry("Service", "Email with Subject " + DeleteMailContainingSubject);
}
}
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException ex)
{
EventLog.WriteEntry("Service","Exception :" + ex.ToString());
}
return true;
}
This is my code for downloading email attachments.

Related

attached .doc is opening properly in pc but in mobile its not opening properly while sending by smtp in .net

im creating .doc file and sending mail. in pc dowloaded file from
attachment is opening properly but in mobile its not opening
properly. only html tags are displaying in smart phones.can u
tell me how to render this .doc file so that in mobile also attached
file can be displayed ?
attached file is not supporting in smartphones .only html tags are
displaying.
can anyone tell in my code how to use docX library in my code?
protected void btnMail_Click(object sender, EventArgs e)
{
DisplayProgressBar();
Response.Clear();
try
{
if (Session["Projectname"] != null && Session["Projectname"].ToString() != string.Empty)
{
string Projname = Session["Projectname"].ToString();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
design.RenderControl(htmlWrite);
string strBuilder = stringWrite.ToString();
string strPath = Request.PhysicalApplicationPath + "\\Temp\\WeeklyReport of " + Projname + ".doc";
LblNoteMsg.Text = strPath;
//code changed to send mails
if (File.Exists(strPath))
{
var counter = 1;
strPath = strPath.Replace(".doc", " (" + counter + ").doc");
while (File.Exists(strPath))
{
strPath = strPath.Replace("(" + counter + ").doc", "(" + (counter + 1) + ").doc");
counter++;
}
}
using (var fStream = File.Create(strPath))
{
fStream.Close();
fStream.Dispose();
}
using(StreamWriter sWriter = new StreamWriter(strPath))
{
sWriter.Write(strBuilder);
sWriter.Close();
sWriter.Dispose();
Response.Clear();
}
DateTime input = DateTime.Now;
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime dats = DateTime.Now.AddDays(delta);
//this week
DateTime monday = input.AddDays(delta);
string MonDate = monday.ToShortDateString();
DateTime sat = monday.AddDays(5);
string SatDate = sat.ToShortDateString();
StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
string body = r.ReadToEnd();
MailMessage Msg = new MailMessage();
string MailId = txtMailId.Text;
foreach (string ss in MailId.Split(",".ToCharArray()))
{
if (string.IsNullOrEmpty(ss) == false)
{
Msg.To.Add(new MailAddress(ss));
}
}
Msg.Bcc.Add(new MailAddress("support#sunlightit.com"));
body = body.Replace("<%MonDate%>", MonDate);
body = body.Replace("<%SatDate%>", SatDate);
Msg.Subject = "Weekly status Report of " + Projname + "," + DateTime.Now.ToShortDateString() + "";
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.Attachments.Add(new Attachment(strPath));
SmtpClient MailServer = new SmtpClient();
try
{
MailServer.Send(Msg);
string reply = (Msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess).ToString();
if (reply == "OnSuccess")
{
txtMailId.Text = "";
tblMail.Visible = false;
lblMsg.ForeColor = System.Drawing.Color.Green;
lblMsg.Text = "Mail has send succesfully";
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Mail delivery unsuccessfull";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "clentscript", "alert('It is being used by another process.Please Try after sometime ');", true);
}
}
You did not make a proper .doc file. A .doc file is not composed of HTML. Word on your computer does know HTML so it will open the file, but likely the program you're using on the mobile devices will just treat it as a corrupted .doc file.
Instead, you should build a proper Word document. There's plenty of libraries for generating .docx Open Office XML Document (Word 2007) files. Find one that works for you needs, and use it.
Write the file on the server path and pass the link to user make the download:
Example:
http://yourapp.com/files/download/051651203210.doc

Getting error that file is in use on server but working fine on local system

I am confused whether it is a server issue or coding problem. My strong guess is that it might be a server issue because it is working fine on my local system.
I have upgraded a Asp.net 1.1 website to 4.0. In the application the a file is created by the values that the user enter on the forms. The file is saved in the attachments folder in the application. After the file is created the email is sent to the administrator with attaching the file as an attachment.
On my local system the email is sent just fine. As the application was built in 1.1 CDO is being used to send the emails. When I publish the application on server then attachment is failed and the following error is displayed,
The process cannot access the file 'E:\HostingSpaces\testuser\testapplication.mydomain.com\wwwroot\eTest\Attachment\4orsysil3dulr1iv1thvpade\ef_Comp.exp' because it is being used by another process.
I have given read, write, delete access to the attachments folder. If there is problem in the code then it should also effect the application on the local system too. I have checked all the StreamWriter is closed everywhere it is used.
If this is a server error then what could be the reason?
Edit:
The code is very old written a long time ago and it was working just fine. What I have done is changed the email sending code and specified the SSL and new Port for sending the SMS. Other then that it was not giving error before.
So below is the function which is used to generate the files when the user submit the forms. There are multiple files generated for each form.
private bool GenerateFile()
{
string strSupportDocFile=string.Empty;
string strBespokeFile=string.Empty;
EFormDetails objEFormDetails=new EFormDetails();
DataRow drEForm=objEFormDetails.ResultRow;
string strDirPath = Server.MapPath(#"Attachment/" + Session.SessionID);
try
{
if (!Directory.Exists(strDirPath))
{
Directory.CreateDirectory(strDirPath);
}
StreamWriter ef_File;
StringBuilder strFile=new StringBuilder();
ef_File = new StreamWriter(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EF_COMP_FILENAME));
if(objEFormDetails._EF_COMP != string.Empty)
{
strFile.Append(objEFormDetails._EF_COMP);
ef_File.WriteLine(strFile.ToString());
ef_File.Close();
sbOnFloppyComp=strFile;
}
ef_File = null;
strFile=null;
StringBuilder ef_Cost=new StringBuilder();
strFile=new StringBuilder();
ef_File = new StreamWriter(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EF_COST_FILENAME));
if(objEFormDetails._EF_COST != string.Empty)
{
strFile.Append(objEFormDetails._EF_COST);
ef_File.WriteLine(strFile.ToString());
ef_File.Close();
sbOnFloppyCost=strFile;
}
GetMemberData();
GetOtherDirectorsData();
if(base.IsGuestUser())
{
string strEmailBody;
strEmailBody=GenerateBody();
string strpackage = strEmailBody;
GetPackageDetails(strpackage);
}
return true;
}
catch(Exception ex)
{
lblError.Text=ex.Message.ToString();
return false;
}
}
GetMemberData() function:
private void GetMemberData()
{
EFormDetails objEFormDetails = new EFormDetails();
DataRow drEForm = objEFormDetails.ResultRow;
if (drEForm != null)
{
string strDirPath = Server.MapPath(#"Attachment/" + Session.SessionID);
eFormation.Business.EFDIR efdir = new eFormation.Business.EFDIR();
eFormationResult objResult;
objResult = efdir.LoadEFDIRData(Convert.ToInt64(drEForm[EFORMData.ID_FIELD]), Convert.ToString(drEForm[EFORMData.COMPANYNAME_FIELD]));// + " " + Convert.ToString(drEForm[EFORMData.LIMITED_FIELD])==DBNull.Value ? string.Empty : drEForm[EFORMData.LIMITED_FIELD])));//give efromid adn comapany name
if (!Directory.Exists(strDirPath))
{
Directory.CreateDirectory(strDirPath);
}
StreamWriter swMember;
StringBuilder sb = new StringBuilder();
swMember = new StreamWriter(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EFDIR_MEMBER_FILENAME));
for (int i = 0; i < objResult.ResultData.Tables[0].Rows.Count; i++)
{
sb.Append(objResult.ResultTable.Rows[i][0].ToString());
sb.Append(Environment.NewLine);
}
sbOnFloppyMember = sb;
swMember.WriteLine(sb.ToString());
swMember.Close();
sb = null;
swMember = null;
}
}
GetOtherDirectorsData() function:
private void GetOtherDirectorsData()
{
EFormDetails objEFormDetails = new EFormDetails();
DataRow drEForm = objEFormDetails.ResultRow;
if (drEForm != null)
{
string strDirPath = Server.MapPath(#"Attachment/" + Session.SessionID);
eFormationResult objResult;
eFormation.Business.EFODIR objefodir = new eFormation.Business.EFODIR();
objResult = objefodir.LoadEFODIRData(Convert.ToInt64(drEForm[EFORMData.ID_FIELD]));//change
if (!Directory.Exists(strDirPath))
{
Directory.CreateDirectory(strDirPath);
}
StreamWriter swMember;
StringBuilder sb = new StringBuilder();
swMember = new StreamWriter(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EFODIR_OTHERDIRECTOR_FILENAME));
for (int i = 0; i < objResult.ResultData.Tables[0].Rows.Count; i++)
{
sb.Append(objResult.ResultTable.Rows[i][0].ToString());
sb.Append(Environment.NewLine);
}
sbOnFloppyOtherDirectors = sb;
swMember.WriteLine(sb.ToString());
swMember.Close();
sb = null;
swMember = null;
}
}
GetPackageDetails() function:
private void GetPackageDetails(String strBodyContent)
{
StreamWriter ef_File;
StringBuilder strFile = new StringBuilder();
ef_File = new StreamWriter(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EF_PACKAGE_FILENAME));
ef_File.WriteLine(strBodyContent);
ef_File.Close();
sbOnFloppyComp = strFile;
}
Now all these above mentioned methods are used to create the files.
Now all these files created are added as attachments in the
MailAttachment attachment = new MailAttachment(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EF_COMP_FILENAME));
mEmailMessage.Attachments.Add(attachment);
MailAttachment attachment = new MailAttachment(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EFDIR_MEMBER_FILENAME));
mEmailMessage.Attachments.Add(attachment);
MailAttachment attachment = new MailAttachment(Server.MapPath(#"Attachment/" + Session.SessionID + #"/" + ConstantsData.EF_COST_FILENAME));
mEmailMessage.Attachments.Add(attachment);
See any error?
I have just added these two lines as the email server is now changed to Office 365.
mEmailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", System.Configuration.ConfigurationSettings.AppSettings["SmtpPort"]);
mEmailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
Make sure you dispose of your Attachments and your mail message. Otherwise a lock can linger.
mail.Attachments.Dispose()
mail.Dispose()

How to attach a file to an email in c#

Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:
Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
My question is where am I going wrong where in this code do I put where I want the file to be saved.
The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
File1.f + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.
It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.
In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.
After you upload your file, pass strSavedLocation, which is the file location you saved the file, to your SendMessage() method.
In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage. strAttachment is the path name to your uploaded file:
var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);
It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.
If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
System.Net.Mail.MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
/*** Added mail attachment handling ***/
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strAttachment);
mailMsg.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
}
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
/*** Moved from SendMessage function ****/
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
strSaveLocation + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, strSaveLocation, "");
}
catch
{
}
}
As for the note about using StringBuilder, I agree, and I would use it like this:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);
Edited To Add:
Also, see Brad's answer above about using ContentDisposition.

I can send the images and rar files but that files was corrupted using asp.net?

i am using asp.net and c#.net to send the mail with large attachments(max 10mb), that the reason i can convert the files, .txt,.doc,.xls file are perfectly sending but images and rar file corrupted what is the problem please give me any suggestion ,
My code is
DataSet ds = SqlHelper.ExecuteDataset(con, "usp_GetEmailSettings", Session["UserID"].ToString());
message.To.Add(ds.Tables[0].Rows[0]["Email"].ToString());
message.CC.Add(ds.Tables[1].Rows[0]["EmailID"].ToString());
message.Subject = ds.Tables[0].Rows[0]["Email_Subject"].ToString();
message.From = new System.Net.Mail.MailAddress(ds.Tables[1].Rows[0]["EmailID"].ToString());
message.Body = ds.Tables[0].Rows[0]["Email_Body"].ToString() +
"<br/><br/> <font size='2.0em'>Submission Number : " +filename+"<br/> DBA Name : " +txtDBAName.Text + "<br/> Insured Name : " +TxtInsured.Text + "<br/> Additional Comments : " + txtcomment.Value ;
message.IsBodyHtml = true;
string attachId;
System.Net.Mail.Attachment at;
// Get the HttpFileCollection and Attach the Multiple files
HttpFileCollection hfc = Request.Files;
if (hfc.Count > 0)
{
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
if (i == 0)
{
string[] ext = System.IO.Path.GetFileName(hpf.FileName).Split('.');
attachId = filename + "." + ext[1];
at = new System.Net.Mail.Attachment(fluuploader.FileContent, attachId);
}
else
{
string[] ext = System.IO.Path.GetFileName(hpf.FileName).Split('.');
attachId = filename + "(" + i + ")" + "." + ext[1];
at = new System.Net.Mail.Attachment(fluuploader.FileContent, attachId);
}
at.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
// at.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
message.Attachments.Add(at);
}
}
}
smtp.Timeout = 9999999;
smtp.Send(message);
web.config my code is
<httpRuntime executionTimeout="240" maxRequestLength="20480"/>
at.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit; i can give the comment in that line doesnot send the large files but all are perfectly working but i have send the large files maximum 10mb , pls give me suggestion
Unless there is some black magic taking place behind the scenes, I think you need to swap out fluuploader.FileContent with hpf.InputStream. Also, I find it helps to set the Position of the InputStream to 0. Your final code inside the for loop should look something like this:
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.InputStream.Position = 0;
if (i == 0)
{
string[] ext = System.IO.Path.GetFileName(hpf.FileName).Split('.');
attachId = filename + "." + ext[1];
at = new System.Net.Mail.Attachment(hpf.InputStream, attachId);
}
else
{
string[] ext = System.IO.Path.GetFileName(hpf.FileName).Split('.');
attachId = filename + "(" + i + ")" + "." + ext[1];
at = new System.Net.Mail.Attachment(hpf.InputStream, attachId);
}
message.Attachments.Add(at);
}
Try this code . This should work I am attaching nearly 25MB zip file
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString() );
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}
if you get error please post back

Using Redemption (Outlook) with a user other than the logged in user - and getting errors

I'm using Redemption dll (http://www.dimastr.com/redemption/) and I've created an exe that accesses my mail box.
I run the exe in Windows Scheduler under my username and it works fine, I get an email sent to me (see below code).
When I change the runas username in Scheduler to someone else and try to access their mail box Profile I get an error. System.IO.FileLoadException
static void Main(string[] args)
{
System.Diagnostics.Debugger.Break();
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "Other User Profile Name";
string ToEmailAddress = "abc.email#xyz.com";
string FromEmailAddress = "abc.email#xyz.com";
string outLookServer = "exchangeServer.com";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = null;
try
{
rdoDefaultFolders olFolderInbox = rdoDefaultFolders.olFolderInbox;
Session = new RDOSession();
RDOFolder objFolder;
Session.LogonExchangeMailbox(outLookUser, outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
sMessageBody +=
"\n mailboxCount: " + mailboxCount.ToString() +
"\n defaultStore: " + defaultStore +
"\n\n";
//RDOStore rmpMetering = Session.Stores.GetSharedMailbox("Name of another mailbox");
//objFolder = rmpMetering.GetDefaultFolder(olFolderInbox);
objFolder = Session.GetDefaultFolder(olFolderInbox);
oItems = objFolder.Items;
int totalcount = objFolder.Items.Count;
if (totalcount > 10) totalcount = 10;
for (int loopcounter = 1; loopcounter < totalcount; loopcounter++)
{
RDOMail oItem = objFolder.Items[loopcounter];
string attachmentName = string.Empty;
foreach (RDOAttachment attachment in oItem.Attachments)
{
attachmentName += attachment.FileName + " ";
if (attachmentName.Trim() == "Data.csv")
{
attachment.SaveAsFile(#"C:\datafiles\" + attachmentName.Trim());
foreach (RDOFolder archiveFolder in objFolder.Folders)
{
if (archiveFolder.Name == "DataFileArchive")
{
oItem.MarkRead(true);
oItem.Move(archiveFolder);
}
}
}
}
sMessageBody += oItem.Subject + " " + attachmentName + "\n";
if ((oItem.UnRead))
{
//Do whatever you need this for
//sMessageBody = oItem.Body;
//oItem.MarkRead(true);
}
}
System.Web.Mail.SmtpMail.Send(ToEmailAddress,FromEmailAddress
, "Data File Processing-" + DateTime.Now.ToString()
,"" + sMessageBody);
}
catch (Exception ex)
{
Session = null;
System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
When I try to run the same exe on another machine with me logged in I get this error,
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass
embly 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken=null
' or one of its dependencies. The system cannot find the file specified.
File name: 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken
=null'
at RPMDataFileProcessing.Program.Main(String[] args)
Has anyone got any ideas on what I'm doing wrong, can Redemption be used in this way?
I got this working in the end by ensuring that the user you are logged in as, has 'full mailbox rights' to the mail box you are trying to see.

Categories

Resources