Sending emails with a PDF attachment (C#) - 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.

Related

c# Base64 in email attachment

I know that i'm stuck in a silly problem...and now i am here with hope, that you can help me. Simple situation: I need to send email with attachment from database. I have done it by myself, but...i don't know why, but attachment in email what was send is incorrect. Preciously attachment contents code, what i get from my database.
My code:
static void IncomeMessage()
{
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx");
SqlCommand cmd = new SqlCommand("Here is my SQL SELECT", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try
{
var AID = dr["ID"].ToString();
var Ids = dr["MessageID"].ToString();
var SuperOrganizationTitle = dr["SuperOrganizationTitle"].ToString();
var Date = dr["Date"].ToString();
var Title = dr["Title"].ToString();
var Description = dr["Description"].ToString();
var DBFile = dr["File"].ToString();
var Filename = dr["FileName"].ToString();
MailMessage oMail = new MailMessage("test#test.com", "guntisvindels#gmail.com", "New message with theme: " + Title, "Message Income: " + Date + " From " + SuperOrganizationTitle + ". Message Content: " + Description);
DBFile = GetBase64(DBFile);
var bytes = Encoding.ASCII.GetBytes(DBFile);
MemoryStream strm = new MemoryStream(bytes);
Attachment data = new Attachment(strm, Filename);
ContentDisposition disposition = data.ContentDisposition;
data.ContentId = Filename;
data.ContentDisposition.Inline = true;
oMail.Attachments.Add(data);
SmtpClient oSmtp = new SmtpClient();
SmtpClient oServer = new SmtpClient("test.test.com");
oServer.Send(oMail);
}
catch (Exception ex)
{
//TraceAdd("Error=" + ex.Message.ToString());
}
}
}
For removing unnessessary data ( tags) from database File field i use this code
public static string GetBase64(string str)
{
var index1 = str.IndexOf("<content>");
index1 = index1 + "<content>".Length;
var index2 = str.IndexOf("</content>");
var kek = Slice(str, index1, index2);
return kek;
}
public static string Slice(string source, int start, int end)
{
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}
When launching my code I can send email to me, and I'll recieve it. But message content attachment with my Base64 code from database File field. Here is a question - Where I got wrong, and how can I recieve email with correct attachment that has been written into database. Thank you for your attention
P.S Attachment in database is written correctly, because K2 integration platform can correctly display it
Here is example what database contain in File column (DBFile)
<file><name>zinojums.html</name><content>PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiIC8+PHN0eWxlPmh0bWwsYm9keXtmb250LWZhbWlseTpBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZjtmb250LXNpemU6MTBwdDt9aDF7Zm9udC1zaXplOjE0cHQ7fWgye2ZvbnQtc2l6ZToxMnB0O31we2JhY2tncm91bmQtY29sb3I6I0Y3RUVEQTttYXJnaW46MDtwYWRkaW5nOjhweDt9aHJ7aGVpZ2h0OjFweDsgYm9yZGVyOjAgbm9uZTsgY29sb3I6ICM1RjlCRDQ7IGJhY2tncm91bmQtY29sb3I6ICM1RjlCRDQ7fTwvc3R5bGU+PC9oZWFkPjxib2R5PjxoMT5JbmZvcm3EgWNpamEgbm8gVmFsc3RzIGllxYbEk211bXUgZGllbmVzdGE8L2gxPjxoMj5Eb2t1bWVudHMgcGllxYZlbXRzPC9oMj48cD5Ob2Rva8S8dSBtYWtzxIF0xIFqYSBOci4gPGI+TEFUVklKQVMgVkFMU1RTIFJBRElPIFVOIFRFTEVWxKpaSUpBUyBDRU5UUlMgQVMgKDQwMDAzMDExMjAzKTwvYj4gaWVzbmllZ3RhaXMgZG9rdW1lbnRzICI8Yj5aacWGYXMgcGFyIGRhcmJhIMWGxJNtxJNqaWVtPC9iPiIgTnIuIDxiPjU1NDYyNTY5PC9iPiBwaWXFhmVtdHMgdW4gaWVrxLxhdXRzIFZJRCBkYXR1YsSBesSTLjxiciAvPjwvcD48IS0tY29udGVudC0tPjxociAvPsWgaXMgZS1wYXN0cyBpciBpenZlaWRvdHMgYXV0b23EgXRpc2tpLCBsxatkemFtIHV6IHRvIG5lYXRiaWxkxJN0LjxiciAvPlBpZXNsxJNndGllcyBWSUQgRWxla3Ryb25pc2vEgXMgZGVrbGFyxJPFoWFuYXMgc2lzdMSTbWFpOiA8YSBocmVmPSJodHRwczovL2Vkcy52aWQuZ292Lmx2Ij5lZHMudmlkLmdvdi5sdjwvYT4uPC9ib2R5PjwvaHRtbD4=</content></file>
Right now the method you're using to create binary data from your string takes no account of the fact the string is base64-encoded specifically.
You need to replace
var bytes = Encoding.ASCII.GetBytes(DBFile);
with
var bytes = Convert.FromBase64String(DBFile);

Getting Error 'File is being used' when trying to delete file c#

I have windows service which periodically fetches data from table and creates excel file and mails it to users.After mail sending I need to delete that file. Have used following code:
public void LABInstrumentExcelGeneration(string filePath) {
try {
string connectionString = GetConnectionString(filePath);
List < LABInstruments > listLABInstrument = null;
listLABInstrument = new List < LABInstruments > ();
listLABInstrument = LABInstrumentBL.GetLABInstrumentList();
if (listLABInstrument.Count > 0) {
using(OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [table2] (SrNo string,CalibrationDoneOn Date);";
cmd.ExecuteNonQuery();
foreach(LABInstruments tc1 in listLABInstrument) {
cmd.CommandText = "INSERT INTO [table2](SrNo,CalibrationDoneOn) VALUES('" + tc1.SrNo + "','" + tc1.CalibrationDoneOn + "');";
cmd.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
}
}
} catch (Exception ex) {}
}
SendMail(filePath, role);
if (File.Exists(filePath)) {
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
But it gives error File is being used by another process.
Ho can I delete file? Moreover, i've used OLEDB for file creation. Is there any other best practise for file creation? Have tried ExcelLibrary, but files created in it does not work in all versions of office so have dropped it.
Try this:
protected virtual bool IsLocked(FileInfo fileName)
{
FileStream fStream = null;
try
{
fStream = fileName.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (fStream != null)
{
fStream.Close();
}
}
return false;
}
And then:
if (File.Exists(filePath))
{
FileInfo myfile = new FileInfo(filePath);
if(IsLocked(myfile))
{
File.Create(filePath).Close();
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
else
{
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
}
I think the problem may be that sendmail returns before it has finished using the file.
Instead of sendmail() I used this function which frees up the file for deletion:
public static void send(string subject, string body, string from, string to, List<string> attachments = null)
{
using (MailMessage message = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
message.Subject = subject;
message.Body = body;
if (attachments != null && attachments.Count > 0)
{
foreach (string s in attachments)
{
if (s != null)
{
/* this code fixes the error where the attached file is
* prepended with the path of the file */
Attachment attachment = new Attachment(s, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(s);
disposition.ModificationDate = File.GetLastWriteTime(s);
disposition.ReadDate = File.GetLastAccessTime(s);
disposition.FileName = Path.GetFileName(s);
disposition.Size = new FileInfo(s).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
}
}
using (SmtpClient client = new SmtpClient())
{
client.Send(message);
}
}
}

Sending mails automatically by console application

Create one console application for sending a birthday wishing mail for company employees is here there is send mail code of only one by one employee I try but can't got a multiple emails id from database
Here Code i try it:
class Program
{
static void Main(string[] args)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["EmpDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("SELECT empemail,EmpDOB,empname,Photo,BdayMessage,CC FROM EmpDetails where datepart(day,EmpDOB)= datepart(day,sysdatetime()) and datepart(month,EmpDOB)=datepart(month,sysdatetime())", con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
ArrayList list_emails = new ArrayList();
int i = 0;
string email, Bday;
int diff;
while (reader.Read())
{
email = reader.GetValue(i).ToString();
list_emails.Add(email); //Add email to a arraylist
i = i + 1 - 1;
}
string todaydate = DateTime.Now.ToString("dd/MM");
Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM"); //date converted
diff = DateTime.Compare(DateTime.Today, Convert.ToDateTime(Bday)); //compare cuurent date and date of birthday from database of emplyees with only day and month
//string Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM");
if (diff == 0)
{
//string Email = reader["EmpEmail"].ToString();
string Name = reader["EmpName"].ToString();
string Photo = reader["Photo"].ToString();
string cc = reader["CC"].ToString();
string Bdaymessage = reader["BdayMessage"].ToString();
string body = "<br><b><i><font Size=4 face=Comic Sans MS color= #FF2B9E> Dear</br><br><font Size=4 face=Comic Sans MS color=#FF2B9E>" + Name + "</i></b>" + "<br>" + "<br><img src=" + Photo + "></body></html></body></html>" + "<br><b><font Size=4 face=Comic Sans MS color=#FF2B9E><i>" + Bdaymessage + "</i></b></br> " + "<br><br><br>";
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(Photo, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
av.LinkedResources.Add(inline);
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.AlternateViews.Add(av);
//msg.To.Add(email);
msg.CC.Add(cc);
msg.Subject = " WIsH YoU MaNy MaNY HaPPy Birthday";
msg.From = new System.Net.Mail.MailAddress("example#gmail.com");
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
NetworkCredential NetCrd = new NetworkCredential("eample#gmail.com", "password");
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
reader.Close();
con.Close();
}
else
{
Console.Write("its a earlier date");
}
}
}
}
catch (Exception ex)
{
Console.Write("There is No Birthday" + ex);
}
}
}
You are getting the multiple users form the database that have birthdays with DataReader in a while loop. You just need to move the email sending code inside the loop.
I would recommend you to extract population report (name, birthday, hiredate, email) as excel and let wishing application take care of everything
At minimal it just need two things excel file with wish details (Date, name, email) and a configuration file (application.properties) and that is it, you are good to go.
Further there various options to run the application locally (Command line, foreground, background, docker, windows scheduler, unix cron etc) Cloud.
Application is highly configurable , you can configure various details like:
Workbook loading options
Image options to send with wishes.
SMTP Configurations
Other application level configurations like, when to send wish, belated wish, logging etc.
Disclaimer : I am the owner of the application

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

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

Categories

Resources