Search Results

Search found 133 results on 6 pages for 'mailmessage'.

Page 4/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • SmtpClient.SendAsync - How to ensure my application doesn't finish before callback?

    - by James
    Hi, I need to send emails asychronously through a console application. I need to do some DB updates on the callback but my application is exiting before the callback code gets run! How can I stop this from happening in a nice manner rather than simply guessing how long to wait before exiting. I would imagine the Async calls get placed in some form of thread? Is it possible to check if any are waiting to be called? Sample Code private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { // Get the unique identifier for this asynchronous operation. String token = (string) e.UserState; if (e.Cancelled) { Console.WriteLine("[{0}] Send canceled.", token); } if (e.Error != null) { Console.WriteLine("[{0}] {1}", token, e.Error.ToString()); } else { // update DB Console.WriteLine("Message sent."); } } public static void Main(string[] args) { var users = Repository.GetUsers(); SmtpClient client = new SmtpClient("Host"); client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); MailAddress from = new MailAddress("[email protected]", "System", Encoding.UTF8); foreach (var user in users) { MailAddress to = new MailAddress(user.Email); MailMessage message = new MailMessage(from, to); message.Body = "This is a test"; message.BodyEncoding = System.Text.Encoding.UTF8; message.Subject = "test message 1" + someArrows; message.SubjectEncoding = System.Text.Encoding.UTF8; string userState = String.Format("Message for user id {0}", user.ID); client.SendAsync(message, userState); message.Dispose(); } // need to wait here until I have received a callback for each message // otherwise the application will exit }

    Read the article

  • ASP.NET-MVC Page: image logo is not displaying while sending the email

    - by Rita
    Hi I have a page that sends an email on ASP.NET MVC Page. All the Text is displaying but the image is not displaying. Any workaround. Appreciate your responses. Here is my code: MailMessage mailMsg = new MailMessage(); mailMsg.IsBodyHtml = true; mailMsg.From = new MailAddress(ConfigurationManager.AppSettings["Email.Sender"]); mailMsg.To.Add(new MailAddress(email)); mailMsg.Subject = "Test mail to display the Logo in the email"; mailMsg.Body = " Test mail to display the Logo in the email; mailMsg.Body += Environment.NewLine + Environment.NewLine + "<html><body><img src=cid:companylogo/><br></body></html>"; //Insert Logo string logoPath = Server.MapPath(Links.Content.images.Amgen_MedInfo_Logo_jpg); // logo is placed in images folder LinkedResource logo = new LinkedResource(logoPath); logo.ContentId = "companylogo"; // done HTML formatting in the next line to display logo AlternateView aView = AlternateView.CreateAlternateViewFromString(mailMsg.Body, new System.Net.Mime.ContentType("text/html")); aView.LinkedResources.Add(logo); mailMsg.AlternateViews.Add(aView); mailMsg.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTP"]); smtpClient.Send(mailMsg);

    Read the article

  • Send Email from worker role (Azure) with attachment in c#

    - by simplyvaibh
    I am trying to send an email(in c#) from worker role(Azure) with an attachment(from blob storage). I am able to send an email but attachment(word document) is blank. The following function is called from worker role. public void sendMail(string blobName) { InitStorage();//Initialize the storage var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); container = blobStorage.GetContainerReference("Container Name"); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); if (File.Exists("demo.doc")) File.Delete("demo.doc"); FileStream fs = new FileStream("demo.doc", FileMode.OpenOrCreate); blob.DownloadToStream(fs); Attachment attach = new Attachment(fs,"Report.doc"); System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage("[email protected]", "[email protected]"); Email.Subject = "Text fax send via email"; Email.Subject = "Subject Of email"; Email.Attachments.Add(attach); Email.Body = "Body of email"; System.Net.Mail.SmtpClient client = new SmtpClient("smtp.live.com", 25); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Credentials = new NetworkCredential("[email protected]", Password); client.Send(Email); fs.Flush(); fs.Close(); Email.Dispose(); } Please tell me where I am doing wrong?

    Read the article

  • Send mail in asp.net

    - by Zerotoinfinite
    Hi Experts, I am using asp.net 3.5 and C#. I want to send mail from asp.net, for that I have got some details from my hosting provider which are these: mail.MySite.net UserName Password But I am unable to send mail through these details, I have done the following changes in my web.config file: <system.net> <mailSettings> <smtp> <network host="mail.MySite.net" port="8080" userName="UserName" password="Password" /> </smtp> </mailSettings> </system.net> Also, at the code behind I am writing this function: MailMessage mail = new MailMessage("[email protected]", "[email protected]"); mail.Subject = "Hi"; mail.Body = "Test Mail from ASP.NET"; mail.IsBodyHtml = false; SmtpClient smp = new SmtpClient(); smp.Send(mail); but I am getting error message as message sending failed. Please let me know what I am doing wrong and what I have to do to make it work fine. Thanks in advance.

    Read the article

  • Email not sent until application closes

    - by Tester101
    I have an application that uses SmtpClient to send E-Mail, but the E-Mails are not sent until the application closes. I have searched and searched to find a solution to the problem, but I am not able to find one. The system does have Symantec anti-virus installed, which could possibly be the problem. Does anybody have a solution to this problem? Here is the code I am using. public class EMail { private string server; public string Server {get{return this.server;}set{this.server = value;}} private string to; public string To {get{return this.to;}set{this.to = value;}} private string from; public string From {get{return this.from;}set{this.from = value;}} private string subject; public string Subject {get{return this.subject;}set{this.subject = value;}} private string body; public string Body {get{return this.body;}set{this.body = value;}} public EMail() {} public EMail(string _server, string _to, string _from, string _subject, string _body) { this.Server = _server; this.To = _to; this.From = _from; this.Subject = _subject; this.Body = _body; } public void Send() { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body); message.IsBodyHtml = true; System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //I have tried this, but it still does not work. //client.ServicePoint.ConnectionLeaseTimeout = 0; try { client.Send(message); } catch(System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } message.Dispose(); } }

    Read the article

  • Sending email via GMail in .NET

    - by VP
    I am getting the following error when I try to send an email in my C# program. I am using Visual Studio 2008 on windows 7. I would paste my code first and then the error: class email_log_files { private string login_username = "my_gmail_id"; private string login_password = "my_gmail_password"; public void send_email() { string src_address = "[email protected]"; string dest_address = "[email protected]"; try { MailMessage email_msg = new MailMessage(); SmtpClient email_client = new SmtpClient(); email_msg.From = new MailAddress(src_address); email_msg.Sender = new MailAddress(src_address); email_msg.ReplyTo = new MailAddress(src_address); email_msg.To.Add(dest_address); email_msg.Subject = "Test"; email_msg.Body = "Body of the message"; NetworkCredential credentials = new NetworkCredential(login_username, login_password); email_client.Credentials = credentials; email_client.Host = "smtp.gmail.com"; email_client.Port = 465; email_client.EnableSsl = true; email_client.Send(email_msg); Console.WriteLine("Message Sent Successfully!!"); Console.ReadLine(); } } } And the error message is as follows: The operation has timed out. Why is it always timing out? I am sure that I have the correct smtp server address and port number for gmail as I have configured my outlook with the same. Any help or ideas?

    Read the article

  • The process cannot access the file because it is being used by another process

    - by Xenon
    I have an asp.net website and I allready did .Dispose() here is my code below; try { MailMessage newMail = new MailMessage(MailFrom, MailTo, MailSubject, MailMsg); if (MailAttachment != "") { Attachment data = new Attachment(MailAttachment, MediaTypeNames.Application.Octet); newMail.Attachments.Add(data); } newMail.BodyEncoding = System.Text.Encoding.UTF8; newMail.IsBodyHtml = true; SmtpClient client = new SmtpClient("192.168.2.205"); client.Credentials = CredentialCache.DefaultNetworkCredentials; client.Send(newMail); newMail.Attachments.Dispose(); newMail.Dispose(); DeleteAttachment(MailAttachment); lblSuccess.Text = "Basvurunuz alinmistir tesekkürler."; lblSuccess.Visible = true; ClearForm(); } catch (Exception ex) { lblSuccess.Text = ex.Message; //lblSuccess.Text = "Bir sorun olustu bir daha deneyiniz."; lblSuccess.Visible = true; } But i' m getting the same error, it' s running fine in my localhost but in server i' m getting this error. How can i fix it?

    Read the article

  • .Net System.Mail.Message adding multiple "To" addresses

    - by Matt Dawdy
    I just hit something I think is inconsistent, and wanted to see if I'm doing something wrong, if I'm an idiot, or... MailMessage msg = new MailMessage(); msg.To.Add("[email protected]"); msg.To.Add("[email protected]"); msg.To.Add("[email protected]"); msg.To.Add("[email protected]"); Really only sends this email to 1 person, the last one. To add multiples I have to do this: msg.To.Add("[email protected],[email protected],[email protected],[email protected]"); I don't get it. I thought I was adding multiple people to the "To" address collection, but what I was doing was replacing it. I think I just realized my error -- to add one item to the collection, use .To.Add(new MailAddress("[email protected]")) If you use just a string, it replaces everything it had in its list. Ugh. I'd consider this a rather large gotcha! Since I answered my own question, but I think this is of value to have in the stackoverflow archive, I'll still ask it. Maybe someone even has an idea of other traps that you can fall into.

    Read the article

  • Can't send smtp email from network using C#, asp.net website

    - by Kaysar
    Hi, I have my code here, it works fine from my home, where my user is administrator, and I am connected to internet via a cable network. But, problem is when I try this code from my work place, it does not work. Shows error: "unable to connect to the remote server" From a different machine in the same network: "A socket operation was attempted to an unreachable network 209.xxx.xx.52:25" I checked with our network admin, and he assured me that all the mail ports are open [25,110, and other ports for gmail]. Then, I logged in with administrative privilege, there was a little improvement, it did not show any error, but the actual email was never received. Please note that, the code was tested from development environment, visual studio 2005 and 2008. Any suggestion will be much appreciated. Thanks in advance try { MailMessage mail_message = new MailMessage("[email protected]", txtToEmail.Text, txtSubject.Text, txtBody.Text); SmtpClient mail_client = new SmtpClient("SMTP.y7mail.com"); NetworkCredential Authentic = new NetworkCredential("[email protected]", "xxxxx"); mail_client.UseDefaultCredentials = true; mail_client.Credentials = Authentic; mail_message.IsBodyHtml = true; mail_message.Priority = MailPriority.High; try { mail_client.Send(mail_message); lblStatus.Text = "Mail Sent Successfully"; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message; } } catch (Exception ex) { lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message; }

    Read the article

  • Sending Email over VPN SmtpException net_io_connectionclosed

    - by Holy Christ
    I am sending an email from a WPF application. When sending as a domain user on the network, the emails sends as expected. However, when I attempt to send email over a VPN connection, I get the following exception: Exception: System.Net.Mail.SmtpException: Failure sending mail. --- System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed. at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) I have tried using impersonation as well as setting the Credentials on the SmtpClient. Neither seem to work: using (new ImpersonateUser("myUser", "MYDOMAIN", "myPass")) { var client = new SmtpClient("myhost.com"); client.UseDefaultCredentials = true; client.Credentials = new NetworkCredential("myUser", "myPass", "MYDOMAIN"); client.Send(mailMessage); } I've also tried using Wireshark to view the message over the wire, but I don't know enough about SMTP to know what I'm looking for. One other variable is that the machine I'm using on the VPN is Vista Business and the machine on the network is Win7. I don't think it's related, but then I wouldn't be asking if I knew the issue! :) Any ideas?

    Read the article

  • Sending a list of mails with SmtpClient

    - by Malcolm Frexner
    I use SendCompletedEventHandler of SmtpClient when sending a list of emails. The SendCompletedEventHandler is only called when have already sent all emails in the list. I expexted, that SendCompletedEventHandler is called one an email is send. Is there something wrong in my code? public void SendAllNewsletters(List<string> recipients) { string mailText = "My Tex"; foreach(string recipient in recipients) { //if this loop takes 10min then the first call to //SendCompletedCallback is after 10min SendNewsletter(mailText,recipient); } } public bool SendNewsletter(string mailText , string emailaddress) { SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword); sc.Credentials = SMTPUserInfo; sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); MailMessage mm = null; mm = new MailMessage(mailText, emailaddress); mm.IsBodyHtml = true; mm.Priority = MailPriority.Normal; mm.Subject = "Something"; mm.Body = "Something"; mm.SubjectEncoding = Encoding.UTF8; mm.BodyEncoding = Encoding.UTF8; //Mail string userState = emailaddress; sc.SendAsync(mm, userState); return true; } public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { // Get the unique identifier for this asynchronous operation. String token = (string)e.UserState; if (e.Error != null) { _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message); } else { _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty); } }

    Read the article

  • sending mail in contact information with c#.net problem? help please..

    - by ilkdrl
    protected void Button2_Click(object sender, EventArgs e) { string ad = TextBox1.Text; string firma = TextBox2.Text; string mail = TextBox3.Text; string tel = TextBox4.Text; string tel2 = TextBox5.Text; string fax = TextBox6.Text; string fax2 = TextBox7.Text; string web = TextBox8.Text; string mesaj = TextBox9.Text; try { string fromAddress = "[email protected]"; string fromName = "user"; string toMail = "[email protected]"; string toNme = "Mr."; string msgSubject = "Contact"; string sifre = "userpassword"; string msgBody = "you have a message; \n" + "\n" + "\n" + "Mesaji Gönderenin Adi :" + ad + "\n" + "Mesaji Gönderen Firma :" + firma + "\n" + "Mesaji Gönderenin Maili :" + mail + "\n" + "Mesaji Gönderenin Tel. Numarasi :" + tel + tel2 + "\n" + "Mesaji Gönderenin Fax Numarasi :" + fax + fax2 + "\n" + "Mesaji Gönderenin Web Adresi :" + web + "\n" + "\n" + "\n" + "" + mesaj + "" + "\n" + "\n" + "=======================================" + "\n"; SmtpClient client = new SmtpClient(); client.Credentials = new System.Net.NetworkCredential(fromAddress, sifre); client.Host = "smtp.gmail.com"; client.Port = 1772; client.EnableSsl = false; MailAddress from = new MailAddress(fromAddress, fromName); MailAddress to = new MailAddress(toMail, toNme); MailMessage message = new MailMessage(from, to); message.Subject = msgSubject; message.Body = msgBody; client.Send(message); Response.Redirect("iletisim.aspx"); } catch (Exception ex) { } AND WEB.CONFIG http://go.microsoft.com/fwlink/?LinkId=169433 -- iam trying to send email but i cant give. Where is my problem. Please help me.

    Read the article

  • mail send using C# code debugging.

    - by riad
    Dear all, I have to send mail using C#.I follow each and every step properly but i cannot send mail using this below code.Can anybody pls help me to solve this issue??I know its an old issue and i read all the related articles on that's site about it.But cannot solved my issue.So pls help me to solve this code.The error is: Failur sending mail.I use System.Net.Mail to do it using System.Net.Mail; string mailTo = emailTextBox.Text; string messageFrom = "[email protected]"; string mailSubject = subjectTextBox.Text; string messageBody = messageRichTextBox.Text; string smtpAddress = "mail.abc.com"; int smtpPort = 25; string accountName = "[email protected]"; string accountPassword = "123"; MailMessage message = new MailMessage(messageFrom, mailTo); message.Subject = mailSubject; message.SubjectEncoding = System.Text.Encoding.UTF8; message.Body = messageBody; message.BodyEncoding = System.Text.Encoding.UTF8; SmtpClient objSmtp = new SmtpClient(smtpAddress, smtpPort); objSmtp.UseDefaultCredentials = false; NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(accountName, accountPassword); objSmtp.Credentials = basicAuthenticationInfo; objSmtp.Send(message); MessageBox.Show("Mail send properly"); Thanks in advance Riad

    Read the article

  • ASP.Net : Error in sending EMail from Google Apps hosted at Godaddy

    - by user279244
    Hello, I want to send EMail from my Website hosted at GoDaddy, and we are using Google Apps for Emails. Here is my code in ASP.Net/ C# MailMessage mMailMessage = new MailMessage(); mMailMessage.From = new MailAddress("[email protected]", "GotFeedback", System.Text.Encoding.UTF8); mMailMessage.To.Add(new MailAddress("[email protected]")); mMailMessage.Subject = "subject"; mMailMessage.SubjectEncoding = System.Text.Encoding.UTF8; mMailMessage.Body = body; mMailMessage.BodyEncoding = System.Text.Encoding.UTF8; mMailMessage.IsBodyHtml = true; mMailMessage.Priority = MailPriority.Normal; SmtpClient mSmtpClient = new SmtpClient(); mSmtpClient.UseDefaultCredentials = false; mSmtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword"); mSmtpClient.Host = "SMTP.GOOGLE.COM"; mSmtpClient.Port = 587; mSmtpClient.EnableSsl = true; try { mSmtpClient.Send(mMailMessage); } catch(Exception e) { string edsf = e.ToString(); } But I am getting Exception that it is unable to connect to remote server. Please help. Thanks

    Read the article

  • c# Sending emails with authentication. standard approach not working

    - by Ready Cent
    I am trying to send an email using the following very standard code. However, I get the error that follow... MailMessage message = new MailMessage(); message.Sender = new MailAddress("[email protected]"); message.To.Add("[email protected]"); message.Subject = "test subject"; message.Body = "test body"; SmtpClient client = new SmtpClient(); client.Host = "mail.myhost.com"; //client.Port = 587; NetworkCredential cred = new NetworkCredential(); cred.UserName = "[email protected]"; cred.Password = "correct password"; cred.Domain = "mail.myhost.com"; client.Credentials = cred; client.UseDefaultCredentials = false; client.Send(message); Mailbox unavailable. The server response was: No such user here. This recipient email address definitely works. To make this account work I had to do some special steps in outlook. Specifically, I had to do change account settings - more settings - outgoing server - my outgoing server requires authentication & use same settings. I am wondering if there is some other strategy. I think the key here is that my host is Server Intellect and I know that some people on here use them so hopefully someone else has been able to get through this. I did talk to support but they said with coding issues I am on my own :o

    Read the article

  • How else can I email a file using ASP.NET?

    - by Jane T
    Hi all, I'm using the code below in a ASP.NET page to send a file via email from our users home computer to a mailbox that is used for receiving work that needs photocopying. The code below works fine when sending a file within our network but fails when our users are at home and connected via our SSL VPN, there appears to be a bug in our VPN where it doesn't allow the file to be temporarily saved on the webserver before being sent via email. Can anyone offer any other suggestions on how to attach a file to a ASP.NET page and have the file sent via email without storing it on the web server? Many thanks Jane. MailMessage mail = new MailMessage(); mail.From = txtFrom.Text; mail.To = txtTo.Text; mail.Cc = txtFrom.Text; mail.Subject = txtSubject.Text; mail.Body = "test" mail.BodyFormat = MailFormat.Html; string strdir = "E:\\TEMPforReprographics\\"; //<-------PROBLEM AREA string strfilename = Path.GetFileName(txtFile.PostedFile.FileName); try { txtFile.PostedFile.SaveAs(strdir + strfilename); string strAttachment = strdir + strfilename; mail.Attachments.Add(new MailAttachment(strdir + strfilename)); SmtpMail.SmtpServer = "172.16.0.88"; SmtpMail.Send(mail); Response.Redirect("Thanks.aspx", true); } catch { Response.Write("An error has occured sending the email or uplocading the file."); } finally { }

    Read the article

  • Error while sending mail (attachment file)

    - by Surya sasidhar
    hi, in my application i am using to send mail with attachments i write the code like this Using System.Net.Mail; MailMessage mail = new MailMessage(); mail.Body = "<html><body><b> Name Of The Job Seeker: " + txtName.Text + "<br><br>" + "The Mail ID:" + txtEmail.Text + "<br><br>" + " The Mobile Number: " + txtmobile.Text + "<br><br>" + "Position For Applied: " + txtPostionAppl.Text + "<br><br>" + "Description " + txtdescript.Text + "<br><br></b></body></html>"; mail.From = new MailAddress ( txtEmail.Text); mail.To .Add (new MailAddress ( mailid)); mail.Priority = MailPriority.High; FileUpload1.PostedFile.SaveAs("~/Resume/" + FileUpload1.FileName); mail.Attachments.Add(filenme); SmtpMail sm = new SmtpMail(); sm.Send(mail); it is giving error at attachment like mail.Attachemts.Add(filena) like this 'System.Collections.ObjectModel.Collection.Add(System.Net.Mail.Attachment)' has some invalid arguments.

    Read the article

  • GridView to excel after create send mail c#

    - by Diego Bran
    I want to send a .xlsx , first I created (It has html code in it) then I used a SMTP server to send it , it does attach the file but when I tried to open it " It says that the file is corrupted etc" any help? Here is my code try { System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); // Render grid view control. gvStock.RenderControl(htw); // Write the rendered content to a file. string renderedGridView = sw.ToString(); File.WriteAllText(@"C:\test\ExportedFile.xls", renderedGridView); // File.WriteAllText(@"C:\test\ExportedFile.xls", p1); } catch (Exception e) { Response.Write(e.Message); } try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("server"); mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); mail.Subject = "Test Mail - 1"; mail.Body = "mail with attachment"; Attachment data = new Attachment("C:/test/ExportedFile.xls"); mail.Attachments.Add(data); SmtpServer.Port = 25; SmtpServer.Credentials = new System.Net.NetworkCredential("user", "pass"); // SmtpServer.EnableSsl = true; SmtpServer.UseDefaultCredentials = false; SmtpServer.Send(mail); } catch( Exception e) { Response.Write(e.Message); }

    Read the article

  • Response as mail attachment

    - by el ninho
    using (MemoryStream stream = new MemoryStream()) { compositeLink.PrintingSystem.ExportToPdf(stream); Response.Clear(); Response.Buffer = false; Response.AppendHeader("Content-Type", "application/pdf"); Response.AppendHeader("Content-Transfer-Encoding", "binary"); Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf"); Response.BinaryWrite(stream.GetBuffer()); Response.End(); } I got this working fine. Next step is to send this pdf file to mail, as attachment using (MemoryStream stream = new MemoryStream()) { compositeLink.PrintingSystem.ExportToPdf(stream); Response.Clear(); Response.Buffer = false; Response.AppendHeader("Content-Type", "application/pdf"); Response.AppendHeader("Content-Transfer-Encoding", "binary"); Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf"); Response.BinaryWrite(stream.GetBuffer()); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add("[email protected]"); message.Subject = "Subject"; message.From = new System.Net.Mail.MailAddress("[email protected]"); message.Body = "Body"; message.Attachments.Add(Response.BinaryWrite(stream.GetBuffer())); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("192.168.100.100"); smtp.Send(message); Response.End(); } I have problem with this line: message.Attachments.Add(Response.BinaryWrite(stream.GetBuffer())); Any help how to get this to work? Thanks

    Read the article

  • Send Automated Email through Windows Service that has an embedded image using C#

    - by Refracted Paladin
    I already have a C# windows service that we use internally to monitor a directory on our network and when it detects a change sends off an email using our internal SMTP server to the specified groups of people. Now I need to embedd an image in that automated email. I understand that I need to create an AlternateView and a Linked Resource and use the Linked Resource's cID in the AlternateView, correct. What I do not understand is where do I put the image? Should I add it to my service project and set Copy to Output Directory = Copy Always? If so, how would I then access when creating my LinkedResource? Also, where do I put the image on the Server hosting the Service? Here is what I have so far but it doesn't seem to work. I don't get any errors, that I am aware of, but I do not get an email either. I am guessing it is looking for the image but that I do not have it in the correct location. // This event is called when an object(file,folder) is created in the srcPath void WatcherCreated(object source , FileSystemEventArgs e) { var folderName = e.Name; var folderPath = e.FullPath; MailMessage mail = new MailMessage(); mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); mail.Subject = "New Enrollment for " + folderName; AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is the plain text view", null, "text/html"); AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image. <img src=cid:enrollProcessID>", null, "text/html"); LinkedResource imageResourceLink = new LinkedResource("EnrollmentProcess.jpg") {ContentId = "enrollProcessID"}; htmlView.LinkedResources.Add(imageResourceLink); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); var smtp = new SmtpClient("internalSMTP"); smtp.Send(mail); }

    Read the article

  • Top 50 ASP.Net Interview Questions & Answers

    - by Samir R. Bhogayta
    1. What is ASP.Net? It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc. 2. What’s the use of Response.Output.Write()? We can write formatted output  using Response.Output.Write(). 3. In which event of page cycle is the ViewState available?   After the Init() and before the Page_Load(). 4. What is the difference between Server.Transfer and Response.Redirect?   In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser.  This provides a faster response with a little less overhead on the server.  The clients url history list or current url Server does not update in case of Server.Transfer. Response.Redirect is used to redirect the user’s browser to another page or site.  It performs trip back to the client where the client’s browser is redirected to the new page.  The user’s browser history list is updated to reflect the new address. 5. From which base class all Web Forms are inherited? Page class.  6. What are the different validators in ASP.NET? Required field Validator Range  Validator Compare Validator Custom Validator Regular expression Validator Summary Validator 7. Which validator control you use if you need to make sure the values in two different controls matched? Compare Validator control. 8. What is ViewState? ViewState is used to retain the state of server-side objects between page post backs. 9. Where the viewstate is stored after the page postback? ViewState is stored in a hidden field on the page at client side.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. 10. How long the items in ViewState exists? They exist for the life of the current page. 11. What are the different Session state management options available in ASP.NET? In-Process Out-of-Process. In-Process stores the session in memory on the web server. Out-of-Process Session state management stores data in an external server.  The external server may be either a SQL Server or a State Server.  All objects stored in session are required to be serializable for Out-of-Process state management. 12. How you can add an event handler?  Using the Attributes property of server side control. e.g. [csharp] btnSubmit.Attributes.Add(“onMouseOver”,”JavascriptCode();”) [/csharp] 13. What is caching? Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file. 14. What are the different types of caching? ASP.NET has 3 kinds of caching : Output Caching, Fragment Caching, Data Caching. 15. Which type if caching will be used if we want to cache the portion of a page instead of whole page? Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code: [xml] <%@ OutputCache Duration=”120? VaryByParam=”CategoryID;SelectedID”%> [/xml] 16. List the events in page life cycle.   1) Page_PreInit 2) Page_Init 3) Page_InitComplete 4) Page_PreLoad 5) Page_Load 6) Page_LoadComplete 7) Page_PreRender 8)Render 17. Can we have a web application running without web.Config file?   Yes 18. Is it possible to create web application with both webforms and mvc? Yes. We have to include below mvc assembly references in the web forms application to create hybrid application. [csharp] System.Web.Mvc System.Web.Razor System.ComponentModel.DataAnnotations [/csharp] 19. Can we add code files of different languages in App_Code folder?   No. The code files must be in same language to be kept in App_code folder. 20. What is Protected Configuration? It is a feature used to secure connection string information. 21. Write code to send e-mail from an ASP.NET application? [csharp] MailMessage mailMess = new MailMessage (); mailMess.From = “[email protected]”; mailMess.To = “[email protected]”; mailMess.Subject = “Test email”; mailMess.Body = “Hi This is a test mail.”; SmtpMail.SmtpServer = “localhost”; SmtpMail.Send (mailMess); [/csharp] MailMessage and SmtpMail are classes defined System.Web.Mail namespace.  22. How can we prevent browser from caching an ASPX page?   We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property: [csharp] Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); [/csharp] 23. What is the good practice to implement validations in aspx page? Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources. 24. What are the event handlers that we can have in Global.asax file? Application Events: Application_Start , Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed,  Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute, Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache Session Events: Session_Start,Session_End 25. Which protocol is used to call a Web service? HTTP Protocol 26. Can we have multiple web config files for an asp.net application? Yes. 27. What is the difference between web config and machine config? Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server. 28.  Explain role based security ?   Role Based Security used to implement security based on roles assigned to user groups in the organization. Then we can allow or deny users based on their role in the organization. Windows defines several built-in groups, including Administrators, Users, and Guests. [xml] <AUTHORIZATION>< authorization > < allow roles=”Domain_Name\Administrators” / >   < !– Allow Administrators in domain. — > < deny users=”*”  / >                            < !– Deny anyone else. — > < /authorization > [/xml] 29. What is Cross Page Posting? When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of  the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted. 30. How can we apply Themes to an asp.net application? We can specify the theme in web.config file. Below is the code example to apply theme: [xml] <configuration> <system.web> <pages theme=”Windows7? /> </system.web> </configuration> [/xml] 31: What is RedirectPermanent in ASP.Net?   RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses. 32: What is MVC? MVC is a framework used to create web applications. The web application base builds on  Model-View-Controller pattern which separates the application logic from UI, and the input and events from the user will be controlled by the Controller. 33. Explain the working of passport authentication. First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page 34. What are the advantages of Passport authentication? All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site. Users can maintain his/ her information in a single location. 35. What are the asp.net Security Controls? <asp:Login>: Provides a standard login capability that allows the users to enter their credentials <asp:LoginName>: Allows you to display the name of the logged-in user <asp:LoginStatus>: Displays whether the user is authenticated or not <asp:LoginView>: Provides various login views depending on the selected template <asp:PasswordRecovery>:  email the users their lost password 36: How do you register JavaScript for webcontrols ? We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method. 37. In which event are the controls fully loaded? Page load event. 38: what is boxing and unboxing? Boxing is assigning a value type to reference type variable. Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable. 39. Differentiate strong typing and weak typing In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime. 40. How we can force all the validation controls to run? The Page.Validate() method is used to force all the validation controls to run and to perform validation. 41. List all templates of the Repeater control. ItemTemplate AlternatingltemTemplate SeparatorTemplate HeaderTemplate FooterTemplate 42. List the major built-in objects in ASP.NET?  Application Request Response Server Session Context Trace 43. What is the appSettings Section in the web.config file? The appSettings block in web config file sets the user-defined values for the whole application. For example, in the following code snippet, the specified ConnectionString section is used throughout the project for database connection: [csharp] <em><configuration> <appSettings> <add key=”ConnectionString” value=”server=local; pwd=password; database=default” /> </appSettings></em> [/csharp] 44.      Which data type does the RangeValidator control support? The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date. 45. What is the difference between an HtmlInputCheckBox control and anHtmlInputRadioButton control? In HtmlInputCheckBoxcontrol, multiple item selection is possible whereas in HtmlInputRadioButton controls, we can select only single item from the group of items. 46. Which namespaces are necessary to create a localized application? System.Globalization System.Resources 47. What are the different types of cookies in ASP.NET? Session Cookie – Resides on the client machine for a single session until the user does not log out. Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never. 48. What is the file extension of web service? Web services have file extension .asmx.. 49. What are the components of ADO.NET? The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection. 50. What is the difference between ExecuteScalar and ExecuteNonQuery? ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

    Read the article

  • Send MIME-encoded file as e-mail in C#

    - by Matthias
    Hi folks, I've got the problem that I have a MIME-encoded file with all relevant mail information (subject, from, to, ...) and want to send it over a defined SMTP server via C#. I've looked at the MailMessage class and searched for a solution, but I couldn't find something fitting. Are you able to help me? Thanks, Matthias

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >