Question

In my web project, I am trying to programmatically send the contents of a text file that exists within the project to a default email address. Are there any simple ways of doing this in C#?

Was it helpful?

Solution

Something like:

// Read the file
string body = File.ReadAllText(@"C:\\MyPath\\file.txt");

MailMessage mail = new MailMessage("you@you.com", "them@them.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
mail.Subject = "file";

// Set the read file as the body of the message
mail.Body = body;

// Send the email
client.Send(mail);

OTHER TIPS

Let say your file is /files/file1.txt

So to read it Use :

var content = System.IO.File.ReadAllText(Server.MapPath("/files/file1.txt"));

And Send It by

MailMessage message = new MailMessage();
message.From = new MailAddress("your email address");
message.To.Add(new MailAddress("the target email address"));
message.Subject = "...";
message.Body = content;

var client = new SmtpClient();
client.Send(message);

Here you have an example:

MailMessage message = new MailMessage();
message.From = new MailAddress("from@from.be");

message.To.Add(new MailAddress("to@to.be"));

message.Subject = "Subject goes here.";
message.Body = File.ReadAllText("Path-to-file");

SmtpClient client = new SmtpClient();
client.Send(message);

You should read the mail outside of construction of the e-mail, but it's here just to show the reading of a file.

Kr,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top