Skip to main content

Schedule Mail Sending with attachment file ASP.NET MVC

For scheduling mail i am using JobcashAction. It's simple

Open your Global.asax.cs file just use the following code.

  public class MvcApplication : System.Web.HttpApplication  
   {  
     // Define Path Of the Job  
     private const string JobCashAction = "http://localhost:38416/Home/AddJobCache";  
     protected void Application_Start()  
     {  
       AreaRegistration.RegisterAllAreas();  
       WebApiConfig.Register(GlobalConfiguration.Configuration);  
       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
       RouteConfig.RegisterRoutes(RouteTable.Routes);  
       BundleConfig.RegisterBundles(BundleTable.Bundles);  
       AuthConfig.RegisterAuth();  
     }  
     protected void Application_BeginRequest(object sender, EventArgs e)  
     {  
       if (HttpContext.Current.Cache["jobkey"] == null)  
       {  
         HttpContext.Current.Cache.Add("jobkey",  
                         "jobvalue", null,  
                         DateTime.MaxValue,  
                         TimeSpan.FromSeconds(15), // set the time interval  
                         CacheItemPriority.Default, JobCacheRemoved);  
       }  
     }  
     private static void JobCacheRemoved(string key, object value, CacheItemRemovedReason reason)  
     {  
       var client = new WebClient();  
       client.DownloadData(JobCashAction);  
       ScheduleJob();  
     }  
     private static void ScheduleJob()  
     {  
       // ExecuteAnyMethod  
     }  
   }  


Now just use the code in you controller as you define in JobcashAction path in Global 

"http://localhost:38416/Home/AddJobCache";

 I use AddJobCache  ActionResult it in my home controller.



 public ActionResult AddJobCache()  
     {  
       // Report data  
       List<Student> studentList = new List<Student>();  
       studentList = GetStudentInfo(); // Get the StudentList Data  
       ReportDocument details = new ReportDocument();  
       details.Load(Server.MapPath("../Report/rptStudent.rpt")); // Crystal report path  
       details.SetDataSource(studentList); // Set the StudentList Data as report source  
       details.ExportToDisk(ExportFormatType.PortableDocFormat, "D:\\ff.pdf"); // save file as pdf  
       // Mail Send  
       MailMessage mail = new MailMessage();  
       SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");  
       mail.From = new MailAddress("atiour.islam@gmail.com"); // Sender Email Address  
       mail.To.Add("atik.kotha@gmail.com"); // Send Mail to  
       mail.Subject = "Test"; // Email Subject  
       mail.Body = "Hi"; // Email Body  
       System.Net.Mail.Attachment attachment;  
       attachment = new System.Net.Mail.Attachment("D:\\ff.pdf");// Get Attach file path  
       mail.Attachments.Add(attachment);  
       SmtpServer.Port = 587;  
       SmtpServer.Credentials = new System.Net.NetworkCredential("atiour.islam@gmail.com", "yourpassword");// Sender Email & Password  
       SmtpServer.EnableSsl = true;  
       SmtpServer.Timeout = 60000;  
       SmtpServer.Send(mail);  
       return null;  
     }  

Enjoy...



Comments

Popular posts from this blog

The calling thread must be STA, because many UI components require this.

Using Thread: // Create a thread Thread newWindowThread = new Thread(new ThreadStart(() => { // You can use your code // Create and show the Window FaxImageLoad obj = new FaxImageLoad(destination); obj.Show(); // Start the Dispatcher Processing System.Windows.Threading.Dispatcher.Run(); })); // Set the apartment state newWindowThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread newWindowThread.IsBackground = true; // Start the thread newWindowThread.Start(); Using Task and Thread: // Creating Task Pool, Each task will work asyn and as an indivisual thread component Task[] tasks = new Task[3]; // Control drug data disc UI load optimize tasks[0] = Task.Run(() => { //This will handle the ui thread :The calling thread must be STA, because many U...

mvvm double click event in listview

If you want to get the double click event on a listview item you can try with this code; <ListView Grid.Row="0" Grid.RowSpan="3" Grid.Column="0" Width="250" Height="200" HorizontalAlignment="Stretch" VerticalAlignment="Top" AlternationCount="2" BorderBrush="#FFA8CC7B" ItemContainerStyle="{StaticResource alternatingStyle}" ItemsSource="{Binding FromPayerNameList}" SelectedItem="{Binding SelectedFromPayer, Mode=TwoWay}"> <ListView.ItemTemplate> <DataTemplate> <TextBlock Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" Text=...

An error occurred while updating the entries. See the inner exception for details.

If you are using EF then you may get the error. This error is not specify where the error exactly occur in your table. To specify the error use this code & use debugger to see the exact error message. try { //Your code db = new FEDALIC_AGRI_DBEntities (); model.FarmerVillage = new Guid(village); model.FarmerThana = new Guid(thana); model.FarmerDistrict = new Guid(district); var _SET_FARMER_INFO = EMFermar.SetToModelObject(model); db.SET_FARMER_INFO.Add(_SET_FARMER_INFO); db.SaveChanges(); } catch (DbUpdateException e) { var innerEx = e.InnerException; while (innerEx.InnerException != null) innerEx = innerEx.InnerException; throw new Exception(innerEx.Message); } catch (DbEntityValidationException e...