Search Results

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

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

  • Wrapping mailmessage headers in .net for Sendgrid

    - by mickyjtwin
    Am using SendGrid for some email notifications, specifically utilising their SMTP API's. While they have PHP examples, c# is not so helpful. Essentially, a json string is built that contains the to email addresses, and other custom filters etc, which is then added to a MailMessage header to send. // json string example {"to":["[email protected]", [email protected]", "", ""],"sub":{"<name>":["Name1", Name2"]}} MailMessage m = new MailMessage("[email protected]", "[email protected]"); m.Headers.Add("X-SMTPAPI", jsonString); The problem I am having is that for some MTA's, headers can only be 1000 characters long, and also quoted-principle encoding required only 76 character per line. In their php example, they are splitting the string and adding a linebreak (\n) every 72 characters. While I am doing this in .NET, I am receiving a invalid character exception. After some digging, it seems that pre-.NET4.0 Beta2 MailMessage will not process CLLR characters. Sengrid support is not proving helpful, and looking at ways to make this work?

    Read the article

  • Getting a sent MailMessage into the "Sent Folder"

    - by Robert Reid
    I'm sending MailMessages with an SmtpClient (being delivered successfully) using an Exchange Server but would like my sent emails to go to the Sent Folder of the email address I'm sending them from (not happening). using (var mailMessage = new MailMessage("[email protected]", "[email protected]", "subject", "body")) { var smtpClient = new SmtpClient("SmtpHost") { EnableSsl = false, DeliveryMethod = SmtpDeliveryMethod.Network }; // Apply credentials smtpClient.Credentials = new NetworkCredential("smtpUsername", "smtpPassword"); // Send smtpClient.Send(mailMessage); } Is there a configuration I'm missing that will ensure all of my sent emails from "[email protected]" arrive in their Sent Folder?

    Read the article

  • Is there a way to serialize a .Net MailMessage object

    - by Matt Dawdy
    I am trying to write a proc that will take in as a parameter a MailMessage object, and the split it apart to store the subject, body, to addresses, from address, and attachments (the hard part) in a database so the email can be sent at some point in the future. My first take on this was to rip out the parts I need and store them in a database, and that works great except for attachments. I can't figure out how to loop through the collection and then actually do anything with them. It there an easy way to serialize a MailMessage object that will actually take the content of the attachments with it? Am I doing this all wrong? Has anyone done this before?

    Read the article

  • Cancel outlook meeting requests via MailMessage in C#

    - by BTmuney
    I'm creating an application using the ASP.NET MVC 1 framework in C#, where I have users that register for events. Upon registering, I create an outlook meeting request public string BuildMeetingRequest(DateTime start, DateTime end, string attendees, string organizer, string subject, string description, string UID, string location) { System.Text.StringBuilder sw = new System.Text.StringBuilder(); sw.AppendLine("BEGIN:VCALENDAR"); sw.AppendLine("VERSION:2.0"); sw.AppendLine("METHOD:REQUEST"); sw.AppendLine("BEGIN:VEVENT"); sw.AppendLine(attendees); sw.AppendLine("CLASS:PUBLIC"); sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow)); sw.AppendLine("DESCRIPTION:" + description); sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end)); sw.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow)); sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start)); sw.AppendLine("ORGANIZER;CN=\"NAME\":mailto:" + organizer); sw.AppendLine("SEQUENCE:0"); sw.AppendLine("UID:" + UID); sw.AppendLine("LOCATION:" + location); sw.AppendLine("SUMMARY;LANGUAGE=en-us:" + subject); sw.AppendLine("BEGIN:VALARM"); sw.AppendLine("TRIGGER:-PT720M"); sw.AppendLine("ACTION:DISPLAY"); sw.AppendLine("DESCRIPTION:Reminder"); sw.AppendLine("END:VALARM"); sw.AppendLine("END:VEVENT"); sw.AppendLine("END:VCALENDAR"); return sw.ToString(); } And once built, I use MailMessage, with an alternate view to send out the meeting request: meetingInfo = BuildMeetingRequest(start, end, attendees, organizer, subject, description, UID, location); System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/calendar; method=REQUEST"); AlternateView ICSview = AlternateView.CreateAlternateViewFromString(meetingInfo,mimeType); MailMessage message = new MailMessage(); message.To.Add(to); message.From = new MailAddress(from); message.AlternateViews.Add(ICSview); SmtpClient client = new SmtpClient(); client.Send(message); When users get the email in outlook, it shows up as a meeting request, as opposed to a normal email. This works well for sending out updates to the meeting request as well. The only problem that I am having is that I do not know the proper format for sending out a cancellation. I've attempted to examine some meeting request cancellations in text editors and can't seem to pinpoint the difference in the format between cancelling/creating. Any help on this is greatly appreciated.

    Read the article

  • How to suppress email validation when using SmtpClient and MailMessage

    - by Matthias
    When sending out emails using the SmtpClient and a MailMessage (.net 3.5) the "To" email address(es) get validated prior to sending. I've got a big stack of email addresses which have a dot (.) before the at-sign, causing a FormatException when you attempt to send the message using the SmtpClient. This is actually a good thing, because by specification a dot before the at-sign is invalid. Unfortunately, those emails exist in the real world and they get delivered, if you send them out using your preferred email client. My question is, can email validation through the SmtpClient/MailMessage be suppressed?

    Read the article

  • Replace System.Net.Mail.MailMessage with manually created message and send it

    - by DEH
    I am trying to send emails that will bounce to a known mailbox. I plan to use VERP. Unfortunately the System.Net.Mail.MailMessage object does not allow me to precisely set the From: and Sender: headers within my email - it forces the values so that the resulting email contains the phrase 'on behalf of', and does not allow me fine control over the relevant mime headers. I therefore plan to manually write mime email messages directly to the pickup directory so that I can independently control the From and Sender headers. My dev box is a Vista box and therefore does not have an SMTP server. I would like to configure the dev box so that I have an SMTP server running on it. I can then turn off the SMTP server, write messages to the pickup dir, then turn on the SMPT server and see how the individual emails that I have written will behave (some delivered, some bounced to a bounce handler on a different email domain, as dictated by the Sender). Two questions: 1. Can anyone recommend an SMTP server that will monitor a pickup directory? 2. If I set headers as follows; From:[email protected]; Sender:[email protected] then the recipient will see the email as having come from [email protected] ( and won't see any reference to [email protected]), but if the mail bounces then the NDR will be sent to [email protected]). It's a real pain to have to do this, but I can't see any way of using System.Net.Mail.MailMessage without it messing up my headers.

    Read the article

  • Send mail via gmail with PowerShell V2's Send-MailMessage

    - by Scott Weinstein
    I'm trying to figure out how to use PowerShell V2's Send-MailMessage with gmail. Here's what I have so far. $ss = new-object Security.SecureString foreach ($ch in "password".ToCharArray()) { $ss.AppendChar($ch) } $cred = new-object Management.Automation.PSCredential "[email protected]", $ss Send-MailMessage -SmtpServer smtp.gmail.com -UseSsl -Credential $cred -Body... I get the following error Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at At foo.ps1:18 char:21 + Send-MailMessage <<<< ` + CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage Am I doing something wrong, or is Send-MailMessage not fully baked yet (I'm on CTP 3)? Edit - two additional restrictions I want this to be non-interactive, so get-credential won't work The user account isn't on the gmail domain, but an google apps registered domain

    Read the article

  • SmtpClient.Send() complains of incorrect no of overloads when passing in MailMessage object

    - by dotnetdev
    Hi, I have this code written in .NET 4.0 using VS2010 Ultimate Beta 2: smtpClient.Send(mailMsg); smtpClient is a reference to SmtpClient (I have the relevant references added), and likewise for mailMsg (is MailMessage) - there are no errors stating anything like check for missing assemblies. However, I keep getting an error saying that I have the incorrect no of overloads, when SmtpClient takes either a MailMessage object or the To address, From address, Subject, etc. Why doesn't this code work? Totally confused. Thanks

    Read the article

  • Exception when creating MailMessage

    - by Julien Poulin
    I'm getting a FormatException telling me the address '[email protected]' is invalid (I'm guessing because of the '-'). Here is the code I'm using: var md = new MailDefinition(); md.BodyFileName = physicalPath; md.Subject = subject; md.From = from; md.CC = cc; md.IsBodyHtml = true; MailMessage mailMessage = md.CreateMailMessage(to, replacements, owner); Is there a bug in the .Net e-mail parser? I am sure this address is valid since it belongs to a friend and I have no problem sending and receiving his e-mails with Outlook. Is there a way to fix this? EDIT: Here is the stacktrace: [FormatException: La chaîne spécifiée n'est pas de la forme requise pour une adresse de messagerie.] System.Net.Mime.MailBnfHelper.ReadMailAddress(String data, Int32& offset, String& displayName) +1141755 System.Net.Mail.MailAddress.ParseValue(String address) +240 System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding) +85 System.Net.Mail.Message..ctor(String from, String to) +122 System.Net.Mail.MailMessage..ctor(String from, String to) +114 System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String recipients, IDictionary replacements, String body, Control owner) +1366 System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String recipients, IDictionary replacements, Control owner) +290 WebNotificationManager.CreateMessage(Page owner, MessageTemplate messageTemplate, ListDictionary replacements, String to, String from, String cc, String subject) in c:\dev\SoccerMania\SoccerMania\App_Code\WebNotificationManager.cs:41 WebNotificationManager.SendMessage(Page owner, MessageTemplate messageTemplate, ListDictionary replacements, String to, String subject) in c:\dev\SoccerMania\SoccerMania\App_Code\WebNotificationManager.cs:22 inscription.bInscription_Click(Object sender, EventArgs e) in c:\dev\SoccerMania\SoccerMania\Inscription.aspx.cs:54 System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +111 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +79 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

    Read the article

  • Can't override "From" address in MailMessage class using .config login credentials

    - by Jeff
    I'm updating some existing code that sends a simple email using .Net's SMTP classes. Sample code is below. The SMTP host is google and login info is contained in the App.config as shown below (obviously not real login info :)). The problem I'm having, and I haven't been able to find any answers Googling, is that I can NOT override the display of the "from" email address that's contained in the "username" attribute off the Network element in the config in the delivered email. In the line below that explicitly sets the From property off the myMailMessage object, that value, "[email protected]" does NOT display when the email is received. It still shows as "[email protected]" from the Network tag. However, the From name "Sparky" does appear in the email. I've tried adding a custom "From" header to the Header property of the myMailMessage but that didn't work either. Is there anyway to login to the smtp server, as shown below using the Network tag credentials, but in the actual email received override the From email address that's displayed? Sample code: MailMessage myMailMessage = new MailMessage(); myMailMessage.Subject = "My New Mail"; myMailMessage.Body = "This is my test mail to check"; myMailMessage.From = new MailAddress("[email protected]", "Sparky"); myMailMessage.To.Add(new MailAddress("[email protected]", "receiver name")); SmtpClient mySmtpClient = new SmtpClient(); mySmtpClient.Send(myMailMessage); in App.config: <system.net> <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network host="smtp.gmail.com" port="587" userName="[email protected]" password="mypassword" defaultCredentials="false"/> </smtp> </mailSettings> </system.net>

    Read the article

  • Permanently Delete MailMessage in Outlook with VBA?

    - by eidylon
    Hello all, I am looking for a way to permanently delete a MailMessage from Outlook 2000 with VBA code. I'd like to do this without having to do a second loop to empty the Deleted items. Essentially, I am looking for a code equivalent to the UI method of clicking a message and hitting SHIFT+DELETE. Is there such a thing? TIA!

    Read the article

  • System.Net.Mail.MailMessage Raw Content / Spam Assassin

    - by Martin
    Hey everyone, What I am trying to do is pass the raw content of an outgoing email to spamassassin in order to calculate a spam score. I am stuck in how I might get the raw content of the email. My C# code currently just constructs the MailMessage and passes it the SmtpClient's Send() method. Before sending, is there a way to get a raw version of the mail message (as the protocol might see it) so that I can pass this to the spamassassin tool for spam assessment? If I've not explained very well, let me know and I'll try to explain better. Thanks in advance, Martin.

    Read the article

  • How to parse the MailMessage object from raw email string

    - by Xmindz
    I have written a program in C# which connects to a POP Server and retrieves raw email message strings from the server using POP3 command RETR. Since the email message being retrieved by the program is in plain text format with all the headers and message body with in the same, its too difficult to extract each header and mail body from the raw string. Could anybody tell me a solution by which I can parse the entire raw text to a System.Net.Mail.MailMessage object? Following is a sample email raw string: +OK 1281 octets Return-Path: <[email protected]> Delivered-To: samplenet-sample:[email protected] X-Envelope-To: [email protected] Received: (qmail 53856 invoked from network); 22 Sep 2012 06:11:46 -0000 Received: from mailwash18.pair.com (66.39.2.18) MIME-Version: 1.0 From: "Deepu" <[email protected]> To: [email protected] Date: 22 Sep 2012 11:41:39 +0530 Subject: TEST Subject Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: quoted-printable Message-Id: <[email protected]> TEST Body .

    Read the article

  • Checkbox in an email

    - by Austin
    I am creating an email using the c# MailMessage and I am trying to add a checkbox that doesn't need to be clicked. The checkboxes will be used for a checklist of what to bring to an event (like a packing list). I have: MailMessage objEmail = new MailMessage(); objEmail.From = new MailAddress("[email protected]"); objEmail.To.Add(new MailAddress("[email protected]")); objEmail.CC.Add(new MailAddress("[email protected]")); objEmail.Bcc.Add(new MailAddress("[email protected]")); objEmail.Subject = "Packing list!"; objEmail.IsBodyHtml = true; objEmail.Body = @"<div width=""800px""> <h3>WHAT TO BRING</h3> <form> <input type=""checkbox"" name=""item"" value=""shirt"">Shirt<br> <input type=""checkbox"" name=""item"" value=""shoes"">Shoes </form></div>"; but when I send the email the checkboxes do not appear in the list. Output in outlook using outlook.com: WHAT TO BRING I have a bike I have a car Output in outlook using Microsoft Outlook: WHAT TO BRING [ ]I have a bike [ ]I have a car Output in outlook using hotmail.com: WHAT TO BRING I have a bike []I have a car So the problem is with the mail client but it is inconsistent what the problem is. I s there any way to make a consistent output? Is there a way with html that works to create the checkboxes or do I just need to include images of a checkbox? Thanks in advance.

    Read the article

  • What does MailMessage.IsBodyHtml do?

    - by Eddie Deyo
    I'm testing sending out some emails via C#, but I can't tell what effect setting IsBodyHtml to true has. Regardless of the value, whatever I send in my Body shows up with a content type of "text/plain", and my HTML shows up tags and all in my email client (gmail). What is that flag actually supposed to do? NOTE: I can send an HTML email just fine by creating an AlternateView with a content type of "text/html", I just want to understand how setting the body is supposed to work.

    Read the article

  • How do I assign a value to a MailMessage ReplyTo property?

    - by Zack Peterson
    I want to set the ReplyTo value for a .NET MailMessage. MailMessage.ReplyTo Property: ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. MailMessage.ReplyToList Property: Gets or sets the list of addresses to reply to for the mail message. But, ReplyToList is ReadOnly. I've tried to use the MailMessage.Headers property like this: mail.Headers.Add("Reply-To", "[email protected]"); as described here: System.Web.Mail, OH MY! But, that doesn't seem to work. How do I set the value(s) of the MailMessage's ReadOnly property ReplyToList?

    Read the article

  • C# how to dynamically cast an object?

    - by JL
    I am building a helper object that has a property called Mailer. In reality Mailer can be either a System.Net.Mail.MailMessage or a Mono.System.Net.Mail.MailMessage. So I would preferably only want 1 declaration of mailer. For example I don't want: private Mono.Mailing.MailMessage MonoMessage = new Mono.Mailing.MailMessage(); private System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage(); I would prefer object mailer; Then in constructor switch (software) { case EnunInternalMailingSoftware.dotnet: this.mailer = new System.Net.Mail.MailMessage(); break; case EnunInternalMailingSoftware.mono: this.mailer = new Mono.Mailing.MailMessage(); break; } The problem is that mailer has no properties at design time. So I can't compile my code. How can this be fixed, am I taking the right approach. Thanks in advance

    Read the article

  • SmtpClient.SendAsync code review

    - by Lieven Cardoen
    I don't know if this is the way it should be done: { ... var client = new SmtpClient {Host = _smtpServer}; client.SendCompleted += SendCompletedCallback; var userState = mailMessage; client.SendAsync(mailMessage, userState); ... } private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { // Get the unique identifier for this asynchronous operation. var mailMessage= (MailMessage)e.UserState; if (e.Cancelled) { Log.Info(String.Format("[{0}] Send canceled.", mailMessage)); } if (e.Error != null) { Log.Error(String.Format("[{0}] {1}", mailMessage, e.Error)); } else { Log.Info("Message sent."); } mailMessage.Dispose(); } Disposing the mailMessage after the client.SendAsync(...) throws an error. So I need to dispose it in the Callback handler.

    Read the article

  • Sending mail using SmtpClient in .net

    - by Manish Gupta
    I am unable to send the mail using smtp client. here is the code: SmtpClient client=new SmtpClient("Host"); client.Credentials=new NetworkCredential("username", "password"); MailMessage mailMessage = new MailMessage(); mailMessage.from="[email protected]"; mailMessage.To.Add("[email protected]"); mailMessage.body="body"; mailMessage.subject="subject"; client.Send(mailMessage); The problem is that when I use this code in ASP.NET application, I do not recieve any mails. When in asp.net I change the from mail address to username given in NetworkCredential, I recieve mails. But in C# windows application, I can get emails, even if sender's email address is not valid. Thanks in advance....

    Read the article

  • .NET: Problems creating email attachment from MemoryStream.

    - by David
    Hi all I'm using the following method to create an attachment from a MemoryStream: public void AddAttachment(Stream stream, string filename, string mimeType) { byte[] buffer = ((MemoryStream) stream).GetBuffer(); Attachment attachment = new Attachment(stream, filename, mimeType); _mail.Attachments.Add(attachment); } Note that the first line is not necessary isn't necessary for the attachment functionality, it's just useful to have the byte[] handy during debugging so that I can see how big it is. (It generally has around 80,000 elements.) The code runs fine and the email is sent. When Outlook receives the email, in the Inbox it displays the attachment symbol, but when you go into the email the attachment isn't there. Unfortunately I don't have access to the mail server to find out more about the email, e.g. what the attachment looks like, its size etc. Can anyone suggest what properties of the MemoryStream argument might tell me if it is in some way invalid for attachment? Or think of anything else I might try? Thank you. David

    Read the article

  • Exchange Server 2007 is altering href value

    - by Mark Kadlec
    I am creating an email going out to internal users with the following code that has a link to an internal directory: <a href="\\abc\123">\\abc\123</a> And for whatever reason, the mail that comes in shows: \\abc\123 and the link points to /abc/123 I am suspecting Exchange Server of somehow altering the mail message to make it less "dangerous", but I am really stuck here since this is a network address, going to internal users! When they click the link it doesn't show the directory. Any help would be much appreciated!

    Read the article

  • sendAsync() does not send mail always in asp.net

    - by SR Dusad
    Hi I am not able to send asynchronous mail in asp.net using c# .Though my code is correct as If I try to send mail 10 times then only of 1 time it is successful,rest of 9 times there is no error message but mail is also not sent at its destination.I am sending data in mail attachment. I want to send a file upto 5MB in size . Any type of help will be appreciated.

    Read the article

  • Sending mail with Gmail Account using System.Net.Mail in ASP.NET

    - by Jalpesh P. Vadgama
    Any web application is in complete without mail functionality you should have to write send mail functionality. Like if there is shopping cart application for example then when a order created on the shopping cart you need to send an email to administrator of website for Order notification and for customer you need to send an email of receipt of order. So any web application is not complete without sending email. This post is also all about sending email. In post I will explain that how we can send emails from our Gmail Account without purchasing any smtp server etc. There are some limitations for sending email from Gmail Account. Please note following things. Gmail will have fixed number of quota for sending emails per day. So you can not send more then that emails for the day. Your from email address always will be your account email address which you are using for sending email. You can not send an email to unlimited numbers of people. Gmail ant spamming policy will restrict this. Gmail provide both Popup and SMTP settings both should be active in your account where you testing. You can enable that via clicking on setting link in gmail account and go to Forwarding and POP/Imap. So if you are using mail functionality for limited emails then Gmail is Best option. But if you are sending thousand of email daily then it will not be Good Idea. Here is the code for sending mail from Gmail Account. using System.Net.Mail; namespace Experiement { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender,System.EventArgs e) { MailMessage mailMessage = new MailMessage(new MailAddress("[email protected]") ,new MailAddress("[email protected]")); mailMessage.Subject = "Sending mail through gmail account"; mailMessage.IsBodyHtml = true; mailMessage.Body = "<B>Sending mail thorugh gmail from asp.net</B>"; System.Net.NetworkCredential networkCredentials = new System.Net.NetworkCredential("[email protected]", "yourpassword"); SmtpClient smtpClient = new SmtpClient(); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = networkCredentials; smtpClient.Host = "smtp.gmail.com"; smtpClient.Port = 587; smtpClient.Send(mailMessage); Response.Write("Mail Successfully sent"); } } } That’s run this application and you will get like below in your account. Technorati Tags: Gmail,System.NET.Mail,ASP.NET

    Read the article

  • SmtpClient and Locked File Attachments

    - by Rick Strahl
    Got a note a couple of days ago from a client using one of my generic routines that wraps SmtpClient. Apparently whenever a file has been attached to a message and emailed with SmtpClient the file remains locked after the message has been sent. Oddly this particular issue hasn’t cropped up before for me although these routines are in use in a number of applications I’ve built. The wrapper I use was built mainly to backfit an old pre-.NET 2.0 email client I built using Sockets to avoid the CDO nightmares of the .NET 1.x mail client. The current class retained the same class interface but now internally uses SmtpClient which holds a flat property interface that makes it less verbose to send off email messages. File attachments in this interface are handled by providing a comma delimited list for files in an Attachments string property which is then collected along with the other flat property settings and eventually passed on to SmtpClient in the form of a MailMessage structure. The jist of the code is something like this: /// <summary> /// Fully self contained mail sending method. Sends an email message by connecting /// and disconnecting from the email server. /// </summary> /// <returns>true or false</returns> public bool SendMail() { if (!this.Connect()) return false; try { // Create and configure the message MailMessage msg = this.GetMessage(); smtp.Send(msg); this.OnSendComplete(this); } catch (Exception ex) { string msg = ex.Message; if (ex.InnerException != null) msg = ex.InnerException.Message; this.SetError(msg); this.OnSendError(this); return false; } finally { // close connection and clear out headers // SmtpClient instance nulled out this.Close(); } return true; } /// <summary> /// Configures the message interface /// </summary> /// <param name="msg"></param> protected virtual MailMessage GetMessage() { MailMessage msg = new MailMessage(); msg.Body = this.Message; msg.Subject = this.Subject; msg.From = new MailAddress(this.SenderEmail, this.SenderName); if (!string.IsNullOrEmpty(this.ReplyTo)) msg.ReplyTo = new MailAddress(this.ReplyTo); // Send all the different recipients this.AssignMailAddresses(msg.To, this.Recipient); this.AssignMailAddresses(msg.CC, this.CC); this.AssignMailAddresses(msg.Bcc, this.BCC); if (!string.IsNullOrEmpty(this.Attachments)) { string[] files = this.Attachments.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string file in files) { msg.Attachments.Add(new Attachment(file)); } } if (this.ContentType.StartsWith("text/html")) msg.IsBodyHtml = true; else msg.IsBodyHtml = false; msg.BodyEncoding = this.Encoding; … additional code omitted return msg; } Basically this code collects all the property settings of the wrapper object and applies them to the SmtpClient and in GetMessage() to an individual MailMessage properties. Specifically notice that attachment filenames are converted from a comma-delimited string to filenames from which new attachments are created. The code as it’s written however, will cause the problem with file attachments not being released properly. Internally .NET opens up stream handles and reads the files from disk to dump them into the email send stream. The attachments are always sent correctly but the local files are not immediately closed. As you probably guessed the issue is simply that some resources are not automatcially disposed when sending is complete and sure enough the following code change fixes the problem: // Create and configure the message using (MailMessage msg = this.GetMessage()) { smtp.Send(msg); if (this.SendComplete != null) this.OnSendComplete(this); // or use an explicit msg.Dispose() here } The Message object requires an explicit call to Dispose() (or a using() block as I have here) to force the attachment files to get closed. I think this is rather odd behavior for this scenario however. The code I use passes in filenames and my expectation of an API that accepts file names is that it uses the files by opening and streaming them and then closing them when done. Why keep the streams open and require an explicit .Dispose() by the calling code which is bound to lead to unexpected behavior just as my customer ran into? Any API level code should clean up as much as possible and this is clearly not happening here resulting in unexpected behavior. Apparently lots of other folks have run into this before as I found based on a few Twitter comments on this topic. Odd to me too is that SmtpClient() doesn’t implement IDisposable – it’s only the MailMessage (and Attachments) that implement it and require it to clean up for left over resources like open file handles. This means that you couldn’t even use a using() statement around the SmtpClient code to resolve this – instead you’d have to wrap it around the message object which again is rather unexpected. Well, chalk that one up to another small unexpected behavior that wasted a half an hour of my time – hopefully this post will help someone avoid this same half an hour of hunting and searching. Resources: Full code to SmptClientNative (West Wind Web Toolkit Repository) SmtpClient Documentation MSDN © Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  

    Read the article

1 2 3 4 5 6  | Next Page >