Can I check if an email address exists using .net? - c#

Ive seen some php examples of how you can ping an inbox(without sending any mail to it) to check whether it exists. I was wondering if anyone knows if this is possible with .net? If it is Im going to write an app to do a bulk check on list of emails i have captured through my site.

SMTP defines the VRFY command for this, but since abuse by spammers totally overwhelmed the number of legitimate uses, virtually every e-mail server in the world is configured to lie.

What you mean about if you writing "check email"? Without sending some unique link for email owner you can't check this, you can only check syntax of email, and connection to smtp.
public static bool isEmail(string inputEmail)
{
inputEmail = NulltoString(inputEmail);
string strRegex = #"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
smtp check
string[] host = (address.Split('#'));
string hostname = host[1];
IPHostEntry IPhst = Dns.Resolve(hostname);
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s= new Socket(endPt.AddressFamily,
SocketType.Stream,ProtocolType.Tcp);
s.Connect(endPt);

No, it is impossible in principle to check if an email exists - independent of language.
There is simply no protocol to do it.
There are some partial solutions, but none of them are reliable.
See How to check if an email address exists without sending an email? for details.

​
1. Get the MX record for the email provider by using following command:
nslookup -type=mx gmail.com
Make call to tcp client to check if email is valid:
private static void Main(string[] args)
{
var gMail = IsEmailAccountValid("gmail-smtp-in.l.google.com", "aa.aa#gmail.com");
Console.WriteLine($"Gmail account is valid - {gMail.ToString()}");
var live = IsEmailAccountValid("live-com.olc.protection.outlook.com", "aa.aa#live.com");
Console.WriteLine($"Live account is valid - {live.ToString()}");
}
private static byte[] BytesFromString(string str)
{
return Encoding.ASCII.GetBytes(str);
}
private static int GetResponseCode(string ResponseString)
{
return int.Parse(ResponseString.Substring(0, 3));
}
private static bool IsEmailAccountValid(string tcpClient, string emailAddress)
{
TcpClient tClient = new TcpClient(tcpClient, 25);
string CRLF = "\r\n";
byte[] dataBuffer;
string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();
/* Perform HELO to SMTP Server and get Response */
dataBuffer = BytesFromString("HELO Hi" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("MAIL FROM:<YourGmailIDHere#gmail.com>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
/* Read Response of the RCPT TO Message to know from google if it exist or not */
dataBuffer = BytesFromString($"RCPT TO:<{emailAddress}>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
var responseCode = GetResponseCode(ResponseString);
if (responseCode == 550)
{
return false;
}
/* QUITE CONNECTION */
dataBuffer = BytesFromString("QUITE" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
tClient.Close();
return true;
}
The MX record can be obtained using code:
var lookup = new LookupClient();
var result = lookup.QueryAsync("gmail.com", QueryType.ANY).Result;
var domainName = result.Additionals[result.Additionals.Count - 1].DomainName.Value;
Using above code find the MX lookup and use that MX lookup to check if email is valid or not.
​

http://www.codicode.com/art/free_asp_net_email_validator_verifier.aspx.
Use the dll reference to your code. It is free both for personal use and redistribution. It checks for the domain name existence without actually sending an email.

This is not foolproof. The best you can do is check syntax and see if the domain name resolves.
Email syntax RegEx:
(?<username>#?[_a-zA-Z0-9-+]+(\.[_a-zA-Z0-9-+]+)*)#(?<domain>[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|arpa|asia|coop|info|jobs|mobi|museum|name|travel)))

protected bool checkDNS(string host, string recType = "MX")
{
bool result = false;
try
{
using (Process proc = new Process())
{
proc.StartInfo.FileName = "nslookup";
proc.StartInfo.Arguments = string.Format("-type={0} {1}", recType, host);
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.ErrorDialog = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
if ((e.Data != null) && (!result))
result = e.Data.StartsWith(host);
};
proc.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
{
if (e.Data != null)
{
//read error output here, not sure what for?
}
};
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit(30000); //timeout after 30 seconds.
}
}
catch
{
result = false;
}
return result;
}

Related

Is it possible pinging with C# like in the CMD?

I'm trying to get IP address of a dns server with the code:
var address = Dns.GetHostAddresses(domain)[0];
Its working on my pc, but when I'm doing it through someone else pc its giving him different result (IPv6 instead of IPv4).
I did try to use the method
var ipV4Address = address.MapToIPv4();
but that just returning the wrong IP address
p.s: btw, when using the command ping dns.address.blabla on both computers the result is the same.
If the domain have IPv4 and IPv6 addresses, you'll get both. Filter by AddressFamily to InterNetwork only (IPv4) instead of InterNetworkV6 (IPv6)
var ipV4Address = Dns.GetHostAddresses(domain)
.First(a => a.AddressFamily == AddressFamily.InterNetwork);
To answer your specific question in the header: Yes, it is. Here's an outline of how to do that:
using System.Net.NetworkInformation;
...
private static bool PingWithResponse(int timeout, string iP, out string response)
{
bool result = false;
using (var p = new Ping())
{
var r = p.Send(iP, timeout);
response = $"Ping to {iP} [{r.Address}]";
if (r.Status == IPStatus.Success)
{
response += $" Successful Response delay = {r.RoundtripTime} ms";
result = true;
}
else
{
response += $" Failed Status: {r.Status}";
}
}
return result;
}

Sending e-mail from Gmail in Xamarin.Forms app

I am trying to send e-mail from within a Xamarin Forms app, using Gmail.
I have created an Interface with only 1 method: SendEmail();
Then, in the Droid project, I added a class which implements said interface. Using the Dependency attribute and getting the implementation of the method in the main project, all is fine, except the following error:
Could not resolve host 'smtp.gmail.com'
This is the actual implementation of the method:
string subject = "subject here ";
string body= "body here ";
try
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("myEmailAddress#gmail.com");
mail.To.Add("anotherAddress#yahoo.com");
mail.Subject = subject;
mail.Body = body;
smtpServer.Credentials = new NetworkCredential("username", "pass");
smtpServer.UseDefaultCredentials = false;
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
Searching around I could not find any details regarding it other that the actual smtp address.
Also, I have used the Less Secure apps procedure from Google, not receiving a credentials error I assume that it can connect to the account just fine.
Hello I have achieve this using the code below, also I have attached a file to the email, using the dependency service I use this methods:
Android:
public static string ICSPath
{
get
{
var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
Intent choserIntent = new Intent(Intent.ActionSend);
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
Java.IO.File filelocation = new Java.IO.File(ICSPath);
var path = Android.Net.Uri.FromFile(filelocation);
// set the type to 'email'
choserIntent.SetType("vnd.android.cursor.dir/email");
//String to[] = { "asd#gmail.com" };
//emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
choserIntent.PutExtra(Intent.ExtraStream, path);
// the mail subject
choserIntent.PutExtra(Intent.ExtraSubject, "Calendar event");
Forms.Context.StartActivity(Intent.CreateChooser(choserIntent, "Send Email"));
return true;
}
iOS:
public static string ICSPath
{
get
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
MFMailComposeViewController mail;
if (MFMailComposeViewController.CanSendMail)
{
mail = new MFMailComposeViewController();
mail.SetSubject("Calendar Event");
//mail.SetMessageBody("this is a test", false);
NSData t_dat = NSData.FromFile(ICSPath);
string t_fname = Path.GetFileName(ICSPath);
mail.AddAttachmentData(t_dat, #"text/v-calendar", t_fname);
mail.Finished += (object s, MFComposeResultEventArgs args) =>
{
//Handle action once the email has been sent.
args.Controller.DismissViewController(true, null);
};
Device.BeginInvokeOnMainThread(() =>
{
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mail, true, null);
});
}
else
{
//Handle not being able to send email
await App.BasePageReference.DisplayAlert("Mail not supported",
StaticData.ServiceUnavailble, StaticData.OK);
}
return true;
}
I hope this helps.
Figured it own finally!
First of all, I was using Android Player by Xamarin, which apparently does not support network connectivity.
So my fix was easy: used an Android Emulator ( any version of it for that matter ) built in Visual Studio Community 2015, and tested network connectivity using the plugin by James Montemagno ( Xam.Plugin.Connectivity on NuGet ).

Getting Command Not Valid Error logging into Exchange Server using POP 3

I have an application that monitors an Exchange Server mailbox for incoming mail. It works on other systems, but for one of our customers we are getting an error: -ERR Command is not valid in this state.
I don't think it has anything to do with the code itself because we get the same error message when we try logging in using Telnet. The error comes when the User is passed. Just for reference, I have added my login code below.
try
{
tcpClient = new TcpClient(Host, Port);
}
catch (SocketException e) { ... }
String response = "";
try
{
streamReader = GetStreamReader(tcpClient);
response = streamReader.ReadLine();
if (response.StartsWith("+OK"))
{
response = SendReceive("USER ", UserName.Trim() + "#" + Domain.Trim());
if (response.StartsWith("+OK"))
response = SendReceive("PASS ", Password);
}
}
catch (Exception e) { ... }
And the SendReceive method is below:
private String SendReceive(String command, String parameter)
{
String result = null;
try
{
String myCommand = command.ToUpper().Trim() + " " + parameter.Trim() + Environment.NewLine;
byte[] data = System.Text.Encoding.ASCII.GetBytes(myCommand.ToCharArray());
tcpClient.GetStream().Write(data, 0, data.Length);
result = streamReader.ReadLine();
}
catch { } // Not logged in...
return result;
}
Some POP3 servers do not allow the USER command to be used until/unless the connection is using SSL.
In other words, you may need to use the STLS command first (if it is supported), or, failing that, you may be required to use a SASL authentication mechanism.
Check the results of the CAPA command for more information.
Oh, and shameless plug: use MailKit instead of trying to roll your own.

Encoder SDK 4 - Push to Publishing Point

I'm coding an application in c# using EC4 SP2 SDK.
I want to publish my file to a media server publishing point. I've searched and found 2 examples regarding seting up and auth on publishing points, but either are from older sdk's or do not work (and are for console). basicly my application doesn't encode nothing, as if it had nothing to encode.
When in degub mode checkpont i can see the correct properties for the source file and for the server.
The encoding process takes 0secs to process. I checked the logs on the server events and i get a warning "the security system has received and auth request that could not be decoded". I just havo no knowledge to break up further than this. Any help would be appreciated.
this is the piece of code:
private void broadcastSourceFileToMediaServer2()
{
using (LiveJob job = new LiveJob())
{
String filetoencode = #"c:\temp\niceday.wmv";
LiveFileSource filesource = job.AddFileSource(filetoencode);
filesource.PlaybackMode = FileSourcePlaybackMode.Loop;
job.ActivateSource(filesource);
job.ApplyPreset(LivePresets.VC1Broadband4x3);
//don't know which one is good to use
job.AcquireCredentials += new EventHandler<AcquireCredentialsEventArgs>(job_AcquireCredentials);
_myUserName = "indes";
_pw = PullPW("indes");
Uri url = new Uri("http://192.168.1.74:8080/live");
PushBroadcastPublishFormat pubpoint = new PushBroadcastPublishFormat();
pubpoint.PublishingPoint = url;
pubpoint.UserName = _myUserName;
pubpoint.Password = _pw;
job.PublishFormats.Add(pubpoint);
job.PreConnectPublishingPoint();
job.StartEncoding();
statusBox.Text = job.NumberOfEncodedSamples.ToString();
job.StopEncoding();
job.Dispose();
}
}
public static string _myUserName { get; set; }
public static SecureString _pw { get; set; }
//codificação de Password a enviar
private static SecureString PullPW(string pw)
{
SecureString s = new SecureString();
foreach (char c in pw) s.AppendChar(c);
return s;
}
static void job_AcquireCredentials(object sender, AcquireCredentialsEventArgs e)
{
e.UserName = _myUserName;
e.Password = _pw;
e.Modes = AcquireCredentialModes.None;
}
Progresses:
I managed to authenticate (at least get a positive audit event) on the server.
I changed from this:
//don't know which one is good to use
job.AcquireCredentials += new EventHandler<AcquireCredentialsEventArgs>(job_AcquireCredentials);
_myUserName = "indes";
_pw = PullPW("indes");
Uri url = new Uri("http://192.168.1.74:8080/live");
PushBroadcastPublishFormat pubpoint = new PushBroadcastPublishFormat();
pubpoint.PublishingPoint = url;
pubpoint.UserName = _myUserName;
pubpoint.Password = _pw;
To this:
job.AcquireCredentials += new EventHandler<AcquireCredentialsEventArgs>(job_AcquireCredentials);
_myUserName = #"mediaservername\user";
_pw = PullPW("user_password");
Uri url = new Uri("http://192.168.1.74:8080/live");
PushBroadcastPublishFormat pubpoint = new PushBroadcastPublishFormat();
pubpoint.PublishingPoint = url;
If you see on one side if had to include the domain (either domain or computername) before username. this changed the failed audit events on the server, so i could eliminate the manual credentials pubpoint.username and pubpoint.Password.
Now I'm just dealing with a lack of output format exception. On to it.
How about using SMOOTH Streaming, I managed to get my project going but I didn't get much more beyond Look below, to the part that has the PUBLISH switch type. ignore the file portion
internal bool StartStream()
{
Busy = true;
// Instantiates a new job for encoding
//
//***************************************Live Stream Archive******************************
if (blnRecordFromFile)
{
// Sets up publishing format for file archival type
FileArchivePublishFormat fileOut = new FileArchivePublishFormat();
// job.ApplyPreset(LivePresets.VC1512kDSL16x9);
// Gets timestamp and edits it for filename
string timeStamp = DateTime.Now.ToString();
timeStamp = timeStamp.Replace("/", "-");
timeStamp = timeStamp.Replace(":", ".");
// Sets file path and name
string path = "C:\\output\\";
string filename = "Capture" + timeStamp + ".ismv";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
fileOut.OutputFileName = Path.Combine(path, filename);
// Adds the format to the job. You can add additional formats as well such as
// Publishing streams or broadcasting from a port
job.PublishFormats.Add(fileOut);
}
//******************************END OF Stream PORTION****************************************
////////////////////////////////////////////////////////////////////////////////////////////////////
//*************************************** Process Files or Live Stream******************************
if (blnRecordFromFile)
{
job.ApplyPreset(LivePresets.VC1IISSmoothStreaming720pWidescreen);
job = new LiveJob();
// Verifies all information is entered
if (string.IsNullOrWhiteSpace(sourcePath) || string.IsNullOrWhiteSpace(destinationPath))
return false;
job.Status += new EventHandler<EncodeStatusEventArgs>(StreamStatus);
LiveFileSource fileSource;
try
{
// Sets file to active source and checks if it is valid
fileSource = job.AddFileSource(sourcePath);
}
catch (InvalidMediaFileException)
{
return false;
}
// Sets to loop media for streaming
// fileSource.PlaybackMode = FileSourcePlaybackMode.Loop;
// Makes this file the active source. Multiple files can be added
// and cued to move to each other at their ends
job.ActivateSource(fileSource);
}
//******************************END OF FILE PORTION****************************************
// Sets up variable for fomat data
switch (publishType)
{
case Output.Archive:
// Verifies destination path exists and if not creates it
try
{
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
}
catch (IOException)
{
return false;
}
FileArchivePublishFormat archiveFormat = new FileArchivePublishFormat();
// Gets the location of the old extention and removes it
string filename = Path.GetFileNameWithoutExtension(sourcePath);
// Sets the archive path and file name
archiveFormat.OutputFileName = Path.Combine(destinationPath, filename + ".ismv");
job.PublishFormats.Add(archiveFormat);
break;
case Output.Publish:
// Setups streaming of media to publishing point
job = new LiveJob();
// Aquires audio and video devices
Collection<EncoderDevice> devices = EncoderDevices.FindDevices(EncoderDeviceType.Video);
EncoderDevice video = devices.Count > 0 ? devices[0] : null;
for (int i = 0; i < devices.Count; ++i)
// devices[i].Dispose();
devices.Clear();
devices = EncoderDevices.FindDevices(EncoderDeviceType.Audio);
EncoderDevice audio = devices.Count > 0 ? devices[0] : null;
for (int i = 1; i < devices.Count; ++i)
devices[i].Dispose();
devices.Clear();
// Checks for a/v devices
if (video != null && audio != null)
{
//job.ApplyPreset(Preset.FromFile(#"C:\Tempura\LivePreset3.xml"));
job.ApplyPreset(LivePresets.H264IISSmoothStreamingLowBandwidthStandard);
job.OutputFormat.VideoProfile.SmoothStreaming = true;
deviceSource = job.AddDeviceSource(video, audio);
// Make this source the active one
job.ActivateSource(deviceSource);
}
else
{
error = true;
}
PushBroadcastPublishFormat publishFormat = new PushBroadcastPublishFormat();
try
{
// checks the path for a valid publishing point
publishFormat.PublishingPoint = new Uri(destinationPath);
}
catch (UriFormatException)
{
return false;
}
// Adds the publishing format to the job
try
{
// job.ApplyPreset(LivePresets.VC1IISSmoothStreaming480pWidescreen);
job.PublishFormats.Add(publishFormat);
job.PreConnectPublishingPoint();
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace.ToString());
}
break;
default:
return false;
}
job.StartEncoding();
return true;
}
Sadly I dont have enough rep to comment, so I have to write it as an answer.
Due to you are starting a live job, in order to stream you should not call job.StopEncoding() right after StartEncoding. I think usually you would use an event to stop the encoding. If you start encoding and immediately stop it, it is only logical you have no, or only a very small output.
I changed your code to the following and it seems work well. I guess your problem is that you disposed the instance of LiveJob class. You have to keep the instance alive before it finished encoding the whole stream. So change the using part and remove the StopEncoding and Dispose will be OK.
private void broadcastSourceFileToMediaServer2()
{
LiveJob job = new LiveJob();
String filetoencode = #"c:\temp\niceday.wmv";
LiveFileSource filesource = job.AddFileSource(filetoencode);
filesource.PlaybackMode = FileSourcePlaybackMode.Loop;
job.ActivateSource(filesource);
job.ApplyPreset(LivePresets.VC1Broadband4x3);
//don't know which one is good to use
job.AcquireCredentials += new EventHandler<AcquireCredentialsEventArgs>(job_AcquireCredentials);
_myUserName = "indes";
_pw = PullPW("indes");
Uri url = new Uri("http://192.168.1.74:8080/live");
PushBroadcastPublishFormat pubpoint = new PushBroadcastPublishFormat();
pubpoint.PublishingPoint = url;
pubpoint.UserName = _myUserName;
pubpoint.Password = _pw;
job.PublishFormats.Add(pubpoint);
job.PreConnectPublishingPoint();
job.StartEncoding();
statusBox.Text = job.NumberOfEncodedSamples.ToString();
}
public static string _myUserName { get; set; }
public static SecureString _pw { get; set; }
//codificação de Password a enviar
private static SecureString PullPW(string pw)
{
SecureString s = new SecureString();
foreach (char c in pw) s.AppendChar(c);
return s;
}
static void job_AcquireCredentials(object sender, AcquireCredentialsEventArgs e)
{
e.UserName = _myUserName;
e.Password = _pw;
e.Modes = AcquireCredentialModes.None;
}

spamassassin check score C# code

Is there a way to check the score in an ASP.Net application? A class or something similar for .Net? How about other Spam Filters out there.
--Edited
I am looking for a way to check the spam score of the email messages in C#.
Here is my super simplified "just check the score" code for connecting to a running Spam Assassin email check from C# which I wrote for http://elasticemail.com. Just setup SA to run on a server and set the access permissions.
Then you can use this code to call it:
public class SimpleSpamAssassin
{
public class RuleResult
{
public double Score = 0;
public string Rule = "";
public string Description = "";
public RuleResult() { }
public RuleResult(string line)
{
Score = double.Parse(line.Substring(0, line.IndexOf(" ")).Trim());
line = line.Substring(line.IndexOf(" ") + 1);
Rule = line.Substring(0, 23).Trim();
Description = line.Substring(23).Trim();
}
}
public static List<RuleResult> GetReport(string serverIP, string message)
{
string command = "REPORT";
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} SPAMC/1.2\r\n", command);
sb.AppendFormat("Content-Length: {0}\r\n\r\n", message.Length);
sb.AppendFormat(message);
byte[] messageBuffer = Encoding.ASCII.GetBytes(sb.ToString());
using (Socket spamAssassinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
spamAssassinSocket.Connect(serverIP, 783);
spamAssassinSocket.Send(messageBuffer);
spamAssassinSocket.Shutdown(SocketShutdown.Send);
int received;
string receivedMessage = string.Empty;
do
{
byte[] receiveBuffer = new byte[1024];
received = spamAssassinSocket.Receive(receiveBuffer);
receivedMessage += Encoding.ASCII.GetString(receiveBuffer, 0, received);
}
while (received > 0);
spamAssassinSocket.Shutdown(SocketShutdown.Both);
return ParseResponse(receivedMessage);
}
}
private static List<RuleResult> ParseResponse(string receivedMessage)
{
//merge line endings
receivedMessage = receivedMessage.Replace("\r\n", "\n");
receivedMessage = receivedMessage.Replace("\r", "\n");
string[] lines = receivedMessage.Split('\n');
List<RuleResult> results = new List<RuleResult>();
bool inReport = false;
foreach (string line in lines)
{
if (inReport)
{
try
{
results.Add(new RuleResult(line.Trim()));
}
catch
{
//past the end of the report
}
}
if (line.StartsWith("---"))
inReport = true;
}
return results;
}
}
Usage is quite easy:
List<RuleResult> spamCheckResult = SimpleSpamAssassin.GetReport(IP OF SA Server, FULL Email including headers);
It will return the list of spam check rules you hit and the resulting score impact.
I am not exactly sure if that's what you are searching for, but there is a C# wrapper that simplifies the communication with a SpamAssassin server on Code Project:
A C# Wrapper for the SpamAssassin Protocol
Hope that helps!

Categories