Tuesday, January 16, 2007

Use SmtpClient to Send Email

In Asp.Net 2.0, we can use SmtpClient to send email.
MailAddress from = new MailAddress(emailfrom);
MailAddress to = new MailAddress(emailto);
MailMessage mm = new MailMessage(from, to);
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = true;
mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))

SmtpClient sc = new SmtpClient();
sc.DeliveryMethod = SmtpDeliveryMethod.Network; // Network;PickupDirectoryFromIis; SpecifiedPickupDirectory
sc.Host = host;
sc.Port = Convert.ToInt32(port)
sc.Credentials = New NetworkCredential(username, password);
sc.Send(mm);

Here AttachmentFile is a FileUpload control inside the page:
<asp:FileUpload ID="AttachmentFile" runat="server" />

If we do not want to specify the Host information, we can config it inweb.config, and SmtpClient will use this setting to connect to SMTP server:
<configuration>
 <system.net>
  <mailSettings>
   <smtp>
    <network host="relayServerHostname" port="portNumber" userName="username" password="password" />
   </smtp>
  </mailSettings>
 </system.net>
 <system.web> ... </system.web>
</configuration>

SmtpClient throws SmtpException exception.

No comments: