ASP.net mvc5 sending email every 7 day? - c#

I'm working on a small project of mine and I'm not sure if what I am trying to do is possible on a web based solution.
And right now it's setup like this, a user post something and that date he posted in the database. What I want to do is if the user doesn't post another thing within 7 days I want to send them an email saying they are "late" or something similar to that.
I know how to send a email in asp.net as my user can request a new password / they need to verify their email. I just don't know how to set it up like I want above ( IF that even is possible )

You need a separate process that checks for, and then sends, the emails. You won't be able to do it in the web application itself, but some kind of service would do it.
This service would just need to periodically check your database for users and the last date they posted. If it's more than 7 days, send that email off.
Remember to record that the email has been sent and check this when determining what emails to send, otherwise you'll get an email sent every time the service checks the database, which might frustrate the user a bit!

sending email in asp is simple. its a code i did before that check if you want to send a file too:
for working with time you have to work with timeSpan and dateTime
its from example in stackoverflow:
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
you have to check if this value is bigger than 7
so code for sending mail is like below but you have to optimize it for your own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
MailMessage mail = new MailMessage();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
lblmessage.Text ="";
mail.To.Add(txtto.Text.Trim());
mail.From = new MailAddress(txtfrom.Text.Trim());
mail.Subject = txtsubject.Text.Trim();
mail.Body = txtbody.Text.Trim();
mail.IsBodyHtml = true;
if (uploader.HasFile)
{
string filename = uploader.PostedFile.FileName;
string filepath=Server.MapPath("uploads//"+filename);
uploader.SaveAs(filepath);
Attachment attach = new Attachment(filepath);
attach.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
mail.Attachments.Add(attach);
}
SmtpClient client = new SmtpClient();
client.Host = "mail.youdomain.com";
client.Credentials = new System.Net.NetworkCredential("email username=info#yourdomain.com", "email passowrd");
client.Send(mail);
lblmessage.Text = "sent with success";
}
catch (Exception ex)
{
lblmessage.Text = ex.Message;
}
}
}

Related

How do you send emails at a specific time with an attachment (SMTP related)

For example I have an attachment that is to be sent at exactly 3:00 pm everyday. No sql data base or anything. Im assuming I could leave visual studio open as the code would be running everyday until it hit 3:00 pm exactly, and then it sends the body of the email and the attachments and then the code stops because it has executed its daily task of the day. I know I have to use something alone the lines of date.time.now = 3:00 pm and then it sends but im not sure how to do an if statement based off of it
I was thinking of trying something along the lines of
if(today == DayOfWeek.Monday)
{
attachments.add()...
}
And repeating it until it says Friday with copy and paste and that would do it daily technically but to set it to send at exactly 3:00 pm while visual studio is running the code and waiting until it hits 3:00pm for it to actually send the attachments and body of the email
try
{
using (SmtpClient client = new SmtpClient("ip", port))
{
client.EnableSsl = false; //always false
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("username", "password");
MailMessage msgObj = new MailMessage();
msgObj.Attachments.Add(new Attachment("filedirectory"));
msgObj.IsBodyHtml = true; //always sets true, if the body contains html it turns text to html
msgObj.To.Add(Destination);
msgObj.From = new MailAddress("somerandom#gmail.com");
msgObj.Subject = YourMessageSubject;
msgObj.Body = messageBody2; //html
client.Send(msgObj);
}
}
catch (System.Exception)
{
Console.WriteLine("somethings broken");
}

How can I send console output to my email? [duplicate]

This question already has answers here:
send email in c#
(7 answers)
Closed 3 years ago.
I want to get help with how to send the console output via email on a click button function in my program.
The variable textBox2.Text contains the text that is being printed out to the console and I want this text to be send automatically on the (button1_Click_1) function.
I have found some solutions on somewhat similar questions but none of them seem to work, I hope I can find a solution here.
My code:
private void textBox2_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(textBox2);
}
private void button1_Click_1(object sender, EventArgs e)
{
//Sending email function with the console output that is being printed from (textBox2.Text) should be here.
Taskbar.Show();
System.Windows.Forms.Application.Exit();
}
Microsoft recommends that MailKit and MimeKit libraries be used for sending emails from C# applications.
Here is the working code snippet in C# for sending an email:
// File name: SendMail.cs
using System;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
namespace SendMail {
class Program
{
public static void Main (string[] args) {
using (var client = new SmtpClient ()) {
// Connect to the email service (Accept ssl certificate)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect ("smtp.friends.com", 587, false);
// Optional step: Send user id, password, if the server requires authentication
client.Authenticate ("emailID", "emailPassword");
// Construct the email message
var message = new MimeMessage();
message.From.Add (new MailboxAddress ("Sender's Name", "sender-email#example.com"));
message.To.Add (new MailboxAddress ("Receiver's Name", "receiver-email#example.com"));
message.Subject = "Automatic email from the application";
message.Body = new TextPart ("plain") { Text = #"Hello Customer, Happy new year!"};
// Send the email
client.Send (message);
// Close the connection with the email server
client.Disconnect (true);
}
}
}
}
More information:
https://github.com/jstedfast/MailKit

Converting to doc file in ASP.NET Core app and attaching doc file to email

I am trying to convert some data I get from my database in my ASP.NET application. So far I came across a very straight forward framework to do that called DocX.
https://www.nuget.org/packages/DocX/
So according to its API I decided that the best way to implement my task would be to first make a documents and save it to server. Then import it from server as stream and attach it to email. But I a doubtfull.
So I go:
var doc = DocX.Create("test.doc");
string f = "sdcdscdsc";
doc.InsertParagraph(f);
doc.Save();
Two things happen here:
1) First I get an exception FileNotFoundException: Could not load file or assembly 'System.IO.Packaging
2) Somehow... when I tried another framework for doing this DocumentCore (https://www.nuget.org/packages/sautinsoft.document/), I guess that installed a missing file and the Save() method started working and saving the file but the files where blank.
Honestly I would really appreciate on best practices to do this task. If anyone has come across similar task please share the methodology used.
The second part is a bit easier. I got the email part sorted but still got no idea how to attach the file. So far the code looks like this:
private static void SendMail()
{
var mailMessage = new MailMessage("xxxxxx#gmail.com", "xxxxxx#gmail.com");
mailMessage.Subject = "Tester ";
mailMessage.Body = "This is the message";
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxxxxxxx#gmail.com",
Password = "xxxxxxxxx"
};
client.EnableSsl = true;
client.Send(mailMessage);
}
Overall it in bits and pieces and I would really appreciate some sharing of experience. Thank you very much.
Part 1 - create doc with content
Had to use DocXCore for ASP.NET Core app.
private void CreateDocument()
{
try
{
var doc = DocX.Create("mytest.docx");
doc.InsertParagraph("Hello my new message");
doc.Save();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Part 2 - sending email
private void SendMail()
{
var mailMessage = new MailMessage("xxxxx#gmail.com", "yzolxxxxxotarev#gmail.com");
mailMessage.Subject = "Tester ASP.NET Boat Inspector";
mailMessage.Body = "This is the message";
var contentPath = _env.ContentRootPath+#"\mytest.docx";
Attachment data = new Attachment(contentPath, MediaTypeNames.Application.Octet);
mailMessage.Attachments.Add(data);
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxxxx#gmail.com",
Password = "xxxxx"
};
client.EnableSsl = true;
client.Send(mailMessage);
}
Works well.

How do you send an RichText Document as the body of an e-mail programatically using SmtpClient with .net

I am writing a WPF .net app to send an e-mail to several people.
I've got the program working so that it sends plain text e-mails using the code below:
private void OnSendEmails(object sender, RoutedEventArgs e)
{
using (SmtpClient smtpClient = new SmtpClient("<mySMTPserver>", <somePort>))
{
smtpClient.Timeout = 10000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("<myusername>", "<mypassword");
foreach (string address in Addresses)
{
try
{
Console.Out.WriteLine("Sending e-mail to: {0}", address);
smtpClient.Send(Sender, address, Subject, Body);
Console.Out.WriteLine("Sent e-mail to: {0}", address);
}
catch (Exception ex)
{
Console.Out.WriteLine("Exception thrown while sending to : {0}\r\n\r\n{1}", address, ex);
}
Console.Out.WriteLine("Sleeping");
Thread.Sleep(Seconds * 1000);
Console.Out.WriteLine("Done Sleeping");
}
}
}
I would like to send several e-mails out to a select group of people to advertise an app that I wrote. However, I want to send them something other than plain text. I can populate a RichTextBox with the content I wish to send, however, I don't know how to send it since SmtpClient just takes a 'string' to represent the body of the e-mail.
So the question is, how do I send the RichTextBox.Document as the Body of my e-mail using .net and SmptClient?
The document itself will contain images, text, and some links that are associated with icons.
try to create an object of type MailMessage:
var msg = new MailMessage(...);
then you can set this property:
msg.IsBodyHtml = true;
and the message body will be rendered in HTML format.
I am not totally sure the RichTextBox would pass HTML or probably RTF which is slightly different, it could be you should convert RTF into HTML with an helper method before assigning the content to msg.Body.

How to open Outlook new mail window c#

I'm looking for a way to open a New mail in Outlook window.
I need programically fill: from, to, subject, body information, but leave this new mail window open so user can verify content / add something then send as normal Outlook msg.
Found that:
Process.Start(String.Format(
"mailto:{0}?subject={1}&cc={2}&bcc={3}&body={4}",
address, subject, cc, bcc, body))
But there is no "From" option (my users have more than one mailbox...)
Any advice(s) ?
I've finally resolved the issue.
Here is piece of code resolving my problem (using Outlook interops)
Outlook.Application oApp = new Outlook.Application ();
Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem ( Outlook.OlItemType.olMailItem );
oMailItem.To = address;
// body, bcc etc...
oMailItem.Display ( true );
Here is what i have tried. It's working as expected.
This application Adding Recipients, adding cc and adding subject and opening a new mail window.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using Outlook = Microsoft.Office.Interop.Outlook;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSendMail_Click(object sender, EventArgs e)
{
try
{
List<string> lstAllRecipients = new List<string>();
//Below is hardcoded - can be replaced with db data
lstAllRecipients.Add("sanjeev.kumar#testmail.com");
lstAllRecipients.Add("chandan.kumarpanda#testmail.com");
Outlook.Application outlookApp = new Outlook.Application();
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
// Thread.Sleep(10000);
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
foreach (String recipient in lstAllRecipients)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
//Add CC
Outlook.Recipient oCCRecip = oRecips.Add("THIYAGARAJAN.DURAIRAJAN#testmail.com");
oCCRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecip.Resolve();
//Add Subject
oMailItem.Subject = "Test Mail";
// body, bcc etc...
//Display the mailbox
oMailItem.Display(true);
}
catch (Exception objEx)
{
Response.Write(objEx.ToString());
}
}
}
You can't do this with mailto. Either your client will have to select the account they are sending from, which defaults to their default account or you will have to provide a mail form and set the headers when you send the e-mail.

Categories