1. Original Entry + Comments2. Write a Comment3. Preview Comment
New comments for this entry are disabled.

August 09, 2005  |  Further adventures with System.Net.Mail  |  14214 hit(s)

Although "adventures" might be too, um, adventuresome a term.

Yesterday I tried my hand at using .NET 2.0 to send an email, which was partly an exercise in trying to suss out how to do that using only IntelliSense.

Today I wanted to attach a graphic and possibly embed a graphic. From the olde days of System.Web.Mail, I knew that attachments are created separately and then added to the message's attachment collection. I almost got this to work using only IntelliSense, but I must be too tired or something. I wanted to attach a .jpg file and could not figure out how to specify that. The System.Net.Mail.Attachment class supports various properties that sounded right -- ContentStream, ContentDisposition, etc. Those seemed ... like a lot of work just to add a graphic. But as noted, I'm not thinking too clearly here, and I was stumped. So I grubbed through the 2.0 docs and discovered (via a nice example, albeit one that won't compile :-) ) that I can pass a file name as a string in the Attachment constructor. D'oh. Why that was clear yesterday and not today is a mystery.

One of the parameters for the Attachment constructor is the media/content type. There's a class for this -- System.Net.Mime.ContentType -- or if you're facile with standard HTTP media types, you can pass the media type as a string. So here's how I constructed the attachment:
Dim attach As New Attachment("MyPic.jpg", System.Net.Mime.MediaTypeNames.Image.Jpeg)
or alternatively:
Dim attach As New Attachment("MyPic.jpg", "image/jpeg")
Then it's easy to add to the message:
I sent this and it came through just fine as an attachment.

I've poked around with the notion of embedding, but I'm not seeing how to do this obviously, so that will be tomorrow.

I did find out one thing that I'd had a question about yesterday. Why is the MailMessage.To property read-only? Duh, it's because it's a collection. Thus:
Ok, then.

Update 12:56 pm I forgot to note that I sussed out the issue with relay permissions. As I noted yesterday, the SMTP host out-and-out refused to relay any messages that did not have a From address inside our domain. But yay, the SmtpClient class now exposes authentication stuff as proper properties (heh), not wacky extended fields like the old Mail class did. There's a Credentials property that you can use, apparently, to pass explicit credentials. But better yet, there's a UseDefaultCredentials Boolean property that I set to true and that apparently used my Windows creds to authenticate me with the Exchange server. So I was able to set To, From, CC, and ReplyTo addresses to whatever I wanted.

All of this reminds me also to speculate strongly, let us say, that the new Mail classes are no longer wrappers around CDO. They are, I believe, rewritten from first principles.