Click here to Skip to main content
15,896,269 members
Articles / Web Development / ASP.NET

Send Email with VB.NET windows application

Rate me:
Please Sign up or sign in to vote.
2.11/5 (8 votes)
13 Mar 2008CPOL2 min read 97.1K   9K   35  
Send email with attachment using windows app by posting to ASP.net application
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
      Request.SaveAs(@"D:\Emailer\RQlog.txt", true);

      string sTo = txtTo.Value;
      string sFrom = txtFrom.Value;
      string sSubject = txtSubject.Value;
      string sBody = txtBody.Value;
      string sFileName=string.Empty;
      //WriteToLog("from page load txtFrom=" + txtFrom.Value + " files=" + Request.Files.Count);


      if (fileToUpload.PostedFile != null)
      {
        sFileName = @"D:\Emailer\"
        + Path.GetFileNameWithoutExtension(fileToUpload.PostedFile.FileName)
        + DateTime.Now.ToString("yyyyMMddHHmmss")
        + Path.GetExtension(fileToUpload.PostedFile.FileName);
        fileToUpload.PostedFile.SaveAs(sFileName);
      }

      //Emailing code goes here
      if (sFrom.Length > 0 && sTo.Length > 0 && sSubject.Length > 0 && sBody.Length > 0)
      {
        MailMessage mail = new MailMessage(sFrom, sTo, sSubject, sBody);
        Attachment mailAttach = new Attachment(sFileName);
        mail.Attachments.Add(mailAttach);
        SmtpClient client = new SmtpClient("127.0.0.1");
        client.Send(mail);
      }
    }
    private void WriteToLog(string content)
    {
      StreamWriter sw = new StreamWriter(@"D:\Emailer\log.txt", false);
      sw.WriteLine(content);
      sw.Close();
    }      
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
.Net dev for last 3 years wanting to learn more!

Comments and Discussions