Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

[How Do I:] Use ASP.NET to Send Email from a Web Site

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
[Microsoft ASP.net] [www.ASP.net] Hi, my name is Chris Pels. In this video we're going to take a look at how you can send email in an ASP.net website. So let's get started. We'll create a sample website. Now the site I'm going to create here for the video demo— it will be here in Visual Basic, but when you download the samples that come with the video, you can also get it in C Sharp. So to get started, what we'll do here is on our default aspx page let's add some UI controls that will allow us to enter things like the From address, the To address, Subject, and the Body of the email. We'll use that as a basis for the code we'll add behind the scenes to actually send the email. So we'll go over here to form, and let's just add a few text boxes. And the first one—we'll just call it the FromAddress. And let's just give that—let's say 35 columns. And we're actually just going to copy that down a few places here, and that will save some time in doing the rest of these. And let's just call this the ToAddress. And we'll just put the same prefix up here on that FromAddress that we created. Then we want to have the subject, so we'll just put that in. We'll give this 50 columns. And we'll give the body of the email— for this one we'll just give it a 256. Just change that txt body. We'll give it a text mode of MultiLine for this, and let's just give it—we'll give this say 6 rows. Okay. Let me just format that a little bit. Let's just go into the design mode and take a quick look. Then we'll add some labels in front of these boxes once we check out their layout. Okay, that looks pretty good. Let's go back over to the source, and let's just change—actually— change that to 75 columns. I was thinking of the max length of 256, so that'll be good there. Let's just put a few labels. So this we'll just put From, we'll space, and we'll put To, Subject, and we'll just put the word Body there so that when you have the sample, it will be really clear what that is. Okay, let's take another quick look in the designer. All right, that looks good. A little—little rough, but that will server our purpose very well for doing the code behind where we're actually going to send emails. So now let's take a look at the code that would implement the sending of the information that we enter here on this form in an email. All right, so now let's add some code to actually send an email from the information on this form. And the first thing I'm going to do is add another UI element, and that'll be a little button where we can take the click event handler for that button and put the code to actually send the email. And we're just going to call this btnSend. And we'll put the label as Send Mail. Now we'll go over to design mode, and we'll get our button click event by just double clicking on the button. Now here we are in the event handler, and the code behind for default aspx. Now there is several classes we're going to use here, and they all reside in a namespace called System.Net.Mail. If you worked with email previously in ASP.net, you may have worked with a namespace called System.Web.Mail, and that namespace and the associated mail classes in that namespace are being depreciated in favor of using the new System.Net.Mail namespace. So the first class we're going to work with is called mailMessage, and that contains all the information about our email message. So we'll create an instance of that, and we'll just call the variable mailMessage after the class name as a System.Net.Mail.MailMessage. And we'll say equal to a new instance of System.Net.Mail.MailMessage. And as you can see, there are 4 overrides for the constructor of the mailMessage class. One is just an empty mailMessage instance. You can then start to add some of the information for the properties of the mailMessage class such as a From and To address— From, To, Subject, and Body, so that's a pretty complete email right there in the constructor as well as instances for the From and To address of what's called the MailAddress class. And we're going to take a look at that class actually in just a moment. So in the video here we're going to actually just create an empty instance of it, and I think this approach, by using the individual classes and properties of mailMessage, will give you a little better feel for the overall class and how it works. And then once you get familiar with how this works by looking at the sample source code, you them may be able to leverage some of those constructor overrides. So now that we have our mailMessage class, we need to add the From address and the To address for our email message, and those are both added through properties of the mailMessage class. So we'll take our mailMessage class, and there's the from address. And as you can see over here in the tool tip, it says that the From address is an instance of the MailAddress class. So we'll set the From address. And to set that we're going to create a new instance of the MailAddress class. So we'll say new and System.Net.Mail.MailAddress. There it is right there. And the constructor of that has 3 overrides. We have the address that your sending it from, and there we go. The address and a display name as well as the display name in coding. So in this case to start with, we're just going to put the address in, which is the first override of the constructor. And that's going to come from our text box, so we'll just put txtFromAddress—there we go—.Text. And we're just going to trim it to make sure we get everything off of it. So there we go. That is what's necessary to get our From address in our mail message. Now let's add the To address, which is who we're sending it to. And so we see that property. And it's a little bit different than the From address because there's only one From address. However, you can send it to multiple addresses, so let me just back that up, and let's just get that to—there we go. And we get the little tool tip again. As you can see, this is a MailAddressCollection. And so what this allows us to do is add one-to-many To addresses to the mail message. So if you wanted to send a mail to multiple people, you would just add multiple instances of the MailAddress class— similar to what we did in the From address. So we're just going to add one To address here in the demo at the moment. So we'll take the add method of that MailAddressCollection, and we'll say, New System.Net.Mail.MailAddress. And in here we're just going to put txtToAddress.Text.Trim. And that will add the To Address to our mail message. So now we've got the basic From and To Address in there. Let's add the subject line from our form. So mailMessage—there we go. As you might expect, there's a property called Subject. It's just the string. So for this one all we have to do is go down to our text box for subject, take the text, trim it out, and there we have the subject. Now the body is similar to the subject, so we'll just take mailMessage.body, and there's the body property. It's also a string, so we'll just set that equal to txtBody, and we'll trim that out as well. So now with just that amount of code, we have our mail message complete and ready to go. So now what we need to do is look at how we would send this mail message. So next we need to create an instance of what's called the smtpClient class, and that's actually the class that we'll be using to physically send the email message. So let's create an instance of that class. So I'm entering a local variable, and we'll call it smtpClient after the class name as a System.Net.Mail.smtpClient. And we'll set that equal to a new instance— Net.Mail.smtpClient. And there's several overrides for the constructor here in the smtpClient class. One is just an empty instance. We can specify the host name here if we want to. We're going to come back to that in a moment. And we can also specify the port for it. However, what we're going to do is just create an empty instance of smtpClient. And now what we need to do is to configure the smtpClient in terms of what is the host that it's going to use to send the email. And the most efficient way to do that is to actually set those values down in the web.config file, and then they're universally available to any instances of the smptClient that you have throughout your application. And alternatively, we could use one of those overrides on the constructor for the smptClient class that we just saw to add a specific host or port address if we wanted to. So let's use the web.config. We'll go over here and open that up. And the settings for the mail are down in a section of the web.config called System.Net. And inside the System.Net element, you'll find a mailSettings element. And inside of that is the smtp element. And then inside of smtp, we'll find an element called network. And one of the attributes of the network is called host. And in here we'd specify the host name of the server that we'll be sending our outbound email. Now during development, my provider is Cox Communication, so I use smtp.east.cox.net. And that sends my emails during development of my website, and then they—I can test that out locally during development. A lot of times what you'll find if you have a hosted solution up in an isp is they might use local hosts as the host address for sending an email. And you may find that on your help file for the isp, or you can inquire up there. Obviously, if you're using your own server, then you would put the host address in here of your own mail server. So we'll just leave that as is. Let me just save this file, and that's all we need to do to set this up. At least initially that will get our email working. Now we'll go back over here. And once the information in the web.config file is all set up, we're ready to go with our smtpClient. And here there are different things to start out with. We're just going to send the email message. And you can see here in the send method there are 2 overrides. One is we could manually put the actual contents of the email in here. Again, this is another alternative. This is a very flexible system in terms of sending an email. We could put the different values of our form text boxes right here in the send method. As I said though, I thought it would be more informative for us to actually create instances of the mailMessage class and the associated MailAddress classes as we've done here in the sample code. Now let me just back it up—there we go. The second is an instance of the mailMessage class, and that's what we have, so we'll just put MailMessage here. And that is ready to go. And, in fact, what we've done here will actually send this email. That's all the code you need to get up and running in sending the basic email message in the application. So we'll put a break point here on line 7. Let's go up and run this in debug mode. We've got a little form, and I'll just send an email from myself to myself. Test Email in How Do I video. This is a text of sending email. Hit the send button. Into our code behind, we'll create our instance of the MailMessage class, then we'll assign the From address, To address, Subject, and Body dimension or stmpClient. We'll just hover over here to see the From address, and you can see it has broken it down. It has the actual address splint into host and user. We've got the To, we've got our Subject, we've got our body text in there. Now we'll just step right through to send, and off our email has been sent. So that's all there is to being able to send a basic email. Now let's go back and just look at a few more aspects of the MailMessage class and some of the other features that you might want to use. Before we go look at some of the other features of MailMessage class, I just wanted to show you the inbound email from our test here to confirm that indeed that test did work. So here it is inbound into Outlook. So that worked nicely. Now let's go back, and we'll look at a few more features of the MailMessage class. And one of the things that I like to look at is the From address because typically I might use a standard format address when I'm sending all my emails. And here's one approach to doing that. Let me just comment out this line. And what I do is I put the address over in the web.config file, and then it can be universally available as the default From address. And, obviously, I could always override that. I've had a situation where I didn't want to use the default address, but it does save you from having to get that address from the user each time on a form like we've done here. To do that, it's pretty straightforward. We'll go over to the web.config, and I'll put that in the app setting, so it will just add an app setting. And the key—let's just call it the FromEmailAddress. And the value—let me just put the same. So we'll just save that. We'll go back over to the code behind. And now I've just commented out what we did in the previous— taking the From address from the form. I'll leave that in here so you have it in case you want to do that approach. So now we'll take the mailMessage instance, go back to the From property, and we'll again set it to a new instance of the System.Net.Mail.MailAddress. And, however, this time what we'll do is we'll go System.Configuration.ConfigurationSettings.AppSettings and in there—or in there we'll put our fromEmailAddress. And we need one more—yeah, there we go. So now what will happen is every time we send an email message, it's going to get the From address from the web.config file. Let me just put a little comment in there to that effect— get From address in web.config. All right. Now let's see, another thing that you might want to take a look at is that in the MailMessage instance that we have here in addition to sending it to someone, we have the standard cc, and that's a collection just like the To address, so you can carbon copy multiple people by putting multiple instances of the mail address in there. And I'll just put that, and I'll put a comment in front of it. And the other one that we have is the corresponding blind carbon copy, and you may find that useful as well. Next what you might find useful is the priority, and priority is a enum, so you'll see we have low, high, and normal priorities. So we could set this to high priority. Next let's take a look at using attachments. And let me just put a comment in there. Now the attachments is a collection on the mail message, so if we go to mailMessage.attachments, you can see from the tool tip that this is a mail— or I should say an attachment collection, so you can have one-to-many attachments. And to add one, it's just like adding the multiple To addresses, so we have the add method. And in here we put a new instance of System.Net.Mail.Attachment. And so here's a special attachment class to attach your file. And in the constructor for attachment, we'll see that there's actually 6 overrides to the constructor. The most simple is a file name, and that's what we'll put in the code in just a moment. You can also, in addition to the file name, specify a media type. Content as a mime content type. You can also stream something directly into the attachment — new instance of an attachment object for the email—give it a name. You've got a media type for the stream and also a content type for the stream. So we'll go with just c:/temp.txt as a little sample of how you might add an attachment to that. And let me just comment that out. Another property on mailMessage that I find useful has to do with text versus HTML format. And I'll just put Text/HTML. And on the mailMessage you'll see there's a property called IsBodyHTML. That's a Boolean. So if we set that to false, now we'd have a text-based message. If we set that to true, then we're going to have obviously a HTML body. So we'll leave that one as false. There is also one other address that we should put up here. I'll put it right next to the blind carbon copy. And that's mailMessage.ReplyTo. So what you can set here is the ReplyTo address for your mailMessage. And we'll just comment that out in case you want to use that property when you're taking the sample source code and implementing it in your own system. And there's one other thing that we should do down here around our Send method. We should put a Try catch block because obviously things could go wrong when we try to send this email. So let me just move that up into the Try catch block. And we have the generic exception class or instance of the generic exception class here by default. It's also a good idea to put a specific exception class called the smtp exception. So we'll just put catch, and we'll just call it smtpExc as a System.Net.Mail.SmtpException. And you can also see the little tool tip that there are several other exceptions, one for failed recipient, singular, and recipients, plural, that you might want to consider in your Try catch block as well. So we'll just put the smtp exception in here. And then obviously we would want to log errors down here, or whatever you might do in terms of flagging or dealing with exceptions. And where this becomes particularly useful is if we had a loop going on here where we're trying to send and iterate through multiple emails to a list of people. You wouldn't want to not have a Try catch block that catches an error with the sending of one of those individual messages because then that would throw you out of the entire loop, and the remaining email messages wouldn't get sent. So a good practice might be to have this Try catch block. If one message fails, you trap that exception. You might log off somewhere that an exception occurred, which email it was, and then the loop would continue, and the remainder of your emails would be sent. So that covers the core features of sending email in an ASP.net website. You can use the sample source code here in the demo as a starting point for your own implementation and extend it from there. One thing that you might want to do is rather than have this sending of the email right here in the code behind for the page, you might want to abstract that out to its own class in say a class library that is associated with your website that way it would be more reusable across multiple websites that you might have. So I encourage you to download the sample source code. As I mentioned, it's available on C Sharp as well as the Visual Basic we used here in the demo. This is Chris Pels. Thanks for watching this video on sending email in an ASP.net website. [Microsoft ASP.net] [www.ASP.net]

Video Details

Duration: 25 minutes and 32 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 5
Posted by: neudesicasp on Aug 27, 2013

In this video Chris Pels shows how to create and send an email in an ASP.NET web site. First, learn about the core classes in the System.Net.Mail namespace for sending mail in an ASP.NET web site. See how to create an email message using the MailMessage class including how to use the MailAddress class for the From address and how to include one or more To addresses. Next, see how email is sent using the SmtpClient class. Finally, learn about the additional options for configuring the email message such as CC, BCC, Priority, and adding attachments.

Caption and Translate

    Sign In/Register for Dotsub to translate this video.