Skip to content

Instantly share code, notes, and snippets.

@mvklingeren
Created August 29, 2019 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mvklingeren/ac1a25dc3ce1792677a06c75a68a1142 to your computer and use it in GitHub Desktop.
Save mvklingeren/ac1a25dc3ce1792677a06c75a68a1142 to your computer and use it in GitHub Desktop.
Sending a .EML file in C# using MailMessage with the SmtpClient
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MailMeml
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello SMTP Eml mailer!");
// SmtpClient client = new SmtpClient("smtp.csnet.nl");
SmtpClient client = new SmtpClient("smtp.tele2.nl");
int proccessedCount = 0;
foreach (var emlFilename in Directory.GetFiles("c:\\temp\\emailsh").Skip(0))
{
Console.WriteLine(emlFilename);
var fileInfo = new FileInfo(emlFilename);
var emlFileMessage = MsgReader.Mime.Message.Load(fileInfo);
MailMessage newMessage = new MailMessage();
if (emlFileMessage.Headers != null)
{
if (emlFileMessage.Headers.From != null)
{
newMessage.From = new MailAddress(emlFileMessage.Headers.From.Address);
}
else
{
Console.WriteLine($"Cannot process mail:{emlFilename}");
return;
}
if (emlFileMessage.Headers.To != null)
{
foreach (var recipient in emlFileMessage.Headers.To)
{
newMessage.To.Add(recipient.Address);
//for testing purpose, use your own mailaddress: newMessage.To.Add("test@mail-to-some-domain.nl");
}
}
newMessage.Bcc.Add(new MailAddress("mvklingeren@intersoftware.nl"));
newMessage.Subject = emlFileMessage.Headers.Subject;
if (emlFileMessage.HtmlBody != null)
{
newMessage.IsBodyHtml = true;
newMessage.Body = System.Text.Encoding.UTF8.GetString(emlFileMessage.HtmlBody.Body);
}
else if (emlFileMessage.TextBody != null)
{
newMessage.Body = System.Text.Encoding.UTF8.GetString(emlFileMessage.TextBody.Body);
}
foreach (var attach in emlFileMessage.Attachments)
{
var copyAttachment = new Attachment(new MemoryStream(attach.Body), attach.FileName);
newMessage.Attachments.Add(copyAttachment);
}
proccessedCount++;
Console.WriteLine("Sending mail:");
Console.WriteLine($"From: {newMessage.From}");
Console.WriteLine($"To: {newMessage.To}");
Console.WriteLine($"Subject: {newMessage.Subject}");
Console.WriteLine($"Bericht: {newMessage.Body}");
Console.WriteLine($"Attachments aantal: {newMessage.Attachments.Count}");
Console.WriteLine($"Processed aantal: {proccessedCount}");
try
{
client.Send(newMessage);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: {0}",
ex.ToString());
}
Thread.Sleep(1000);
}
}
Console.ReadKey();
}
}
}
@mvklingeren
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment