I have a page that have fileupload control, on the submission of the form, when the fileupload control has file, file is sent via attachment in a mail and working absulutly fine, but when the fileupload control does not have file, ATT00006.dat file is automatically sent via email attachment.
Reference URL: http://nextech.pk/Enquiry.aspx?Enq=cu
Advance Thanks for any help
Edit -- Code:
hpf = fup1.PostedFile;
String toEmail = "test#hotmail.com";
String fromEmail = "mailer#hotmail.com";
MailMessage objMail = new MailMessage(fromEmail, toEmail);
objMail.IsBodyHtml = true;
StringBuilder MailBody = new StringBuilder();
MailBody.Append("<html><head></head><body> <br>");
MailBody.Append("<br>" + "An enquiry is filed <br><br>");
MailBody.Append("<strong><u>Enquirer Information</u></strong>" + "<br><br>");
MailBody.Append("<strong>Contact Name:</strong> " + txtFirstName.Text + "<br>");
MailBody.Append("<strong>Email:</strong> " + txtEmail.Text + "<br>");
MailBody.Append("<strong>Institute:</strong> " + txtInstitute.Text + "<br>");
MailBody.Append("<strong>Phone #:</strong> " + txtPhone.Text + "<br>");
MailBody.Append("<br><strong>Description:</strong><br> " + txtEnquiry.Text + "<br>");
if (hpf != null)
{
MailBody.Append("<br>" + "This email also contains an attachment:- <Strong>(" + hpf.FileName + ")</Strong><br>");
}
MailBody.Append("</body></html>");
objMail.Body = MailBody.ToString();
if (hpf != null)
{
System.IO.Stream inputStream = hpf.InputStream;
String fileName = hpf.FileName;
Attachment attach = new Attachment(inputStream, fileName);
objMail.Attachments.Add(attach);
}
SmtpClient SmtpClnt = new SmtpClient();
SmtpClnt.Send(objMail);
I don't know if you ever got an answer to this, but I've recently studied the problem in detail. The problem occurs because you did not provide an explicit name for the attachment. ASP.NET will always attach as .DAT unless the name is explicitly defined.
The problem is that people assume ASP.NET will use the Filename as the attachment name, which doesn't happen!
In your code, you should create an instance of the attachment, then provide the name explicitly using the FileUpload.FileName property:
Dim att As New System.Net.Mail.Attachment(fu.PostedFile.InputStream, System.Net.Mime.MediaTypeNames.Application.Octet) ' use Octet for binary files '
att.Name = fu.FileName ' get the file name and type automatically '
mm.Attachments.Add(att)
A full explanation of ASP.NET attaching .DAT files is available here
Its a mis-match in the attachment type that the system doesn't understand. Please post your code and what you do when there is not file as an attachment.
I think the mail server you are using (or antivirus software used by the mail server) is automatically adding this file.
Does the file in question contain anything, or is it empty?
Related
Update 1 : I think schema.ini is incorrect. Please refer to below question.
The file (dsTextFile) has just one row of data but record count is zero. So it means it is not reading at all. This is with removing FMT altogether or with Delimi. I still get error if FMT is fixed though. So, how do I create SCHEMA.ini or make sure schema.ini is correct?
private bool LoadTextFile(string textFilePath, out string errorInfo) {
errorInfo = String.Empty;
try {
string textFileFolder = (new System.IO.FileInfo(textFilePath)).DirectoryName;
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Fixed\";";
OleDbConnection textConnection = new OleDbConnection(textConnectionString);
textConnection.Open();
textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
string selectCommand = "select * from " + textFilePath;
OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
textOpenCommand.Connection = textConnection;
OleDbDataAdapter textDataAdapter = new OleDbDataAdapter(textOpenCommand);
Console.WriteLine("Trying to set textDataAdapter");
int rows = textDataAdapter.Fill(dsTextFile); //This is where error is coming.
Console.WriteLine("detail rows being filled");
textConnection.Close();
textConnection.Dispose();
return true;
}
catch (Exception ex_load_text_file) {
Console.WriteLine("error in loadTextFile is " + ex_load_text_file.Message.ToString());
return false;
}
}
Please find the above source where I am getting error 'UnSpecified" for below line.
UnSpecified Error is coming at below line
int rows = textDataAdapter.Fill(dsTextFile)
What could be the issue? I have checked user permissions on c:\windows\temp but no success.
This is a console application and I have even tried to add below code in app.config but no success yet.
<system.web>
<identity imperonate = "false"/> </system.web>
This is a legacy application but needs to run on windows server 2012 setup.
You are using FMT=Fixed on the connection string, if you are not using a schema.ini, change it to FMT=Delimited and it will work.
i.e.:
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Delimited\";";
I'm using System.IO.File.Copy to copy files from serverA to serverB. This works fine accept when the file exsist I get an error "File already exist". I tried trapping it using if file.exsist and nothing.
here is my code.
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("../pdf/audits/" & FileName))
'Local Server
Dim localPath As String = "\\server01\folder1$\pdf\audits\"
'Remote Server
Dim remotePath As String = "\\server02\folder2$\pdf\audits\"
System.IO.File.Copy(localPath + FileName, remotePath + FileName)
What am I missing?
If you just modify your copy operation like this, it should work. The last parameter will overwrite the file.
System.IO.File.Copy(localPath + FileName, remotePath + FileName, True);
If you have large files, you are not going to want to overwrite them everytime. Try fixing your check to see if the file exist. Something like this (C#):
var localPath = #"C:\";
var remotePath = #"\\server\folder\";
var fileName = "test.txt";
if (!new System.IO.FileInfo(remotePath + fileName).Exists)
{
System.IO.File.Copy(localPath + fileName, remotePath + fileName);
}
There's a third parameter to overwrite if it already exists
System.IO.File.Copy(fileName, destName, overwrite);
I got it working with help from RLG.
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("../pdf/audits" & FileName))
'SIGAR Public CMS
Dim localPath As String = "\\hqdadev01\sigar_cms$\pdf\audits\"
'SIGAR Dev
Dim remotePath As String = "\\hqdadev02\sigar_public$\pdf\audits\"
Added this to check.
If Not New System.IO.FileInfo(remotePath + FileName).Exists Then
File.Copy(localPath + FileName, remotePath + FileName, overwrite)
End If
In Web application, I'm trying to send mail to the user with an attachment, I'm sending mail to user but it is not in a good format this is my mail format which is written in asp.net.
StringBuilder stbldr =new StringBuilder();
stbldr.Append("<html><body>
<a href='http://*****/xyxi/mycheck/CheckAttachment.aspx?attid=" + s + "&Eid=" + t + "&afile=" + attach+ "' target='_blank'>Attachment..</a> " + cnt + " <br>
</body> </html>");
when mail send to user, the format in mail is same like above, it is displaying in all tags also like
try
message.Body = stbldr.ToString();
message.BodyFormat = MailFormat.Html;
message.From = txtemail.Text;
message.To = "xxx";
message.Subject = "test";
SmtpMail.SmtpServer = "sxxxxt";
SmtpMail.Send(message);
specify body format as html
First of all, I am a php developer and most of .net is alien to me which is why I am posting here!
I just migrated over a site from one set of webhosting to another. The whole site is written in .net. None of the site is database driven so most of it works, except for the contact form. The output on the site simple states there was an error with "There has been an error - please try to submit the contact form again, if you continue to experience problems, please notify our webmaster." This is just a simple message it pops out of it gets to the "catch" part of the email function.
I went into web.config and changed the parameters:
<emailaddresses>
<add name="System" value="roeland#hoyespharmacy.com"/>
<add name="Contact" value="roeland#bythepixel.com"/>
<add name="Info" value="roeland#bythepixel.com"/>
</emailaddresses>
<general>
<add name="WebSiteDomain" value="hoyespharmacy.com"/>
</general>
Then the .cs file for contact contains the mail function EmailFormData():
private void EmailFormData()
{
try
{
StringBuilder body = new StringBuilder();
body.Append("Name" + ": " + txtName.Text + "\n\r");
body.Append("Phone" + ": " + txtPhone.Text + "\n\r");
body.Append("Email" + ": " + txtEmail.Text + "\n\r");
body.Append("Fax" + ": " + txtEmail.Text + "\n\r");
body.Append("Subject" + ": " + ddlSubject.SelectedValue + "\n\r");
body.Append("Message" + ": " + txtMessage.Text);
MailMessage mail = new MailMessage();
mail.IsBodyHtml = false;
mail.To.Add(new MailAddress(Settings.GetEmailAddress("System")));
mail.Subject = "Contact Us Form Submission";
mail.From = new MailAddress(Settings.GetEmailAddress("System"), Settings.WebSiteDomain);
mail.Body = body.ToString();
SmtpClient smtpcl = new SmtpClient();
smtpcl.Send(mail);
}
catch
{
Utilities.RedirectPermanently(Request.Url.AbsolutePath + "?messageSent=false");
}
}
How do I see what the actual error is. I figure I can do something with the "catch" part of the function.. Any pointers?
Thanks!
Change the catch to
catch(Exception ex)
{
throw;
}
The ex variable will hold your exception information, so you can put a breakpoint there. It'd be easier to step through it, but you can just throw the error as well.
Comment out Utilities.RedirectPermanently(Request.Url.AbsolutePath + "?messageSent=false");
and replace it with throw;
What development environment are you using?
It's probably best to use Visual Studio (Express if you don't have the full version), and debug this code, hitting F11 to step through each statement until it breaks. Then you should have access to more information.
I would suggest logging in the long term (such as log4net). But for the sake of speed try changing your catch statement to look like:
catch(Exception e)
and then use the debugger in VS to explore the actual exception.
Place a breakpoint on the first line of the EmailFormData method and run the application in debug mode. You can then step through the code line by line.
Is it possible to upload a file directly into an ftp account folder with ASP.NET ?
E.g. I click on browse, select a file to upload and when I click "upload" button, It should save it directly to the folder on another web server located at somewhere else other then the server that is being used to upload.
As I understand your question, you want to upload the file to another remote server (so it's not another server sitting on the same network as your web server)? In that case you can do a couple of different things. The easiest way is perhaps to start by making a regular file upload you your server, and then have your server send the file via FTP to the other remote server:
string fileName = Path.Combine("<path on your server", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadFile(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
localFile);
}
...or it might work doing it in one step:
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadData(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
FileUpload1.FileBytes);
}
(I din't try this code out, so there could be some errors in it...)
Update: I noticed that I was wrong in assuming that the UploadXXX methods of WebClient were static...
You can use the WebClient class to store the uploaded file to FTP (without saving it as a file on the server). Something like this:
string name = Path.GetFileName(UploadControl.FileName);
byte[] data = UploadControl.FileBytes;
using (WebClient client = new WebClient()) {
client.UploadData("ftp://my.ftp.server.com/myfolder/" + name, data);
}
/// <summary>
/// Example call : if (FtpUpload(FileUploadControl1, "ftp.my.com/somePathDir", #"user", "pass!", "domain"))
/// </summary>
/// <param name="file"></param>
/// <param name="ftpServer"></param>
/// <param name="username"></param>
/// <param name="ftpPass"></param>
/// <returns></returns>
private bool FtpUpload(FileUpload file, string ftpServer, string username, string ftpPass, string domainName = "")
{
// ftp://domain\user:password#ftpserver/url-path
// If you are a member of a domain, then "ftp://domain-name\username:password#url-path" may fail because the backslash (\) is sent in as a literal character and Internet Explorer incorrectly looks for a file instead of parsing a Web address. Changing the backslash (\) in the domain-name\username to domainname%5Cusername works correctly.
try
{
string ftpAddres;
if (domainName != string.Empty)
ftpAddres = "ftp://" + domainName + #"%5C" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
else
ftpAddres = "ftp://" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
using (var webClient = new System.Net.WebClient())
{
webClient.UploadData(new Uri(ftpAddres), file.FileBytes);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return true;
}
You cannot upload it to an FTP directly from your HTML form. However, you can upload it to your ASP.NET application and then upload it to the FTP from there using FtpWebRequest.
EDIT
First off the # sign is there to flag the string as a literal. it saves you having to escape characters like backslashes. e.g.
string path = "Z:\\Path\\To\\File.txt";
string path = #"Z:\Path\To\File.txt";
Secondly, if you only have FTP Access to the other server, then you can take, the FileUpload.FileBytes Property of the FileUpload control. That will give you a byte[] of the file contents.
From this you use the System.Net.FtpWebRequest & System.Net.FtpWebResponse to upload your file to the FTP Account.
Theres some sample code here in VB.NET but it should be easy enough for you to figure out
http://www.programmingforums.org/thread15954.html
ORIG
The file upload control will provide you with the File on your webserver.
It would be up to you, to copy/save that file then from the webserver to whatever server
you're FTP is hosted on.
Do you have a UNC Path/Mapped Drive shared out on your other server that you can save to.
The FileUpload Control has a .SaveAs() method so it's just a simple matter of
if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(#"Z:\Path\On\Other\Server\" + FileUpload1.FileName);
}