send email with EnableSSL= true throw AuthenticationException - email

I used the following code to send my email with EnableSsl = true,the throw the following exception:
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
public static void SendEmailBySmtpServer(int currentSendCount)
{
try
{
var emailBodyJson = "Period Send Email From Service at -" + DateTime.Now +" Times="+currentSendCount;
emailBodyJson += " EnableSsl=" + ConfigurationManager.AppSettings["SmtpServer.EnableSsl"];
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string fromEmailAddress = appSettings["SmtpServer.FromEmailAddress"];
string toEmailAddress = appSettings["SmtpServer.UserFeedback.ToEmailAddress"];
string host = appSettings["SmtpServer.Host"];
var smtpClient = new SmtpClient(host);
var message = new MailMessage();
message.From = new MailAddress(fromEmailAddress);
message.To.Add(new MailAddress(toEmailAddress));
message.Subject = emailBodyJson;
message.IsBodyHtml = true;
message.Body = emailBodyJson;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = Convert.ToBoolean(appSettings["SmtpServer.EnableSsl"]);//if this changed to true then send failed
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(message);
logger.Info("Send Email Count = "+currentSendCount);
}
catch (Exception ex)
{
logger.Error(ex);
}

To send an email you can use the following code, its working, But you have to use the appropriate .jar files.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "xxxx"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "xxxxx"; // GMail password
private static String RECIPIENT = "xxxxx#xxxx.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ..this is a test mail,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
// String host="localhost";
// props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.host", host);
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");//587
props.put("mail.smtp.auth", "true");
//System.out.println("success point 1");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
// System.out.println("success point 2");
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
//System.out.println("success point 3");
message.setSubject(subject);
message.setText(body);
// System.out.println("success point 4");
Transport transport = session.getTransport("smtp");
// System.out.println("success point 5");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
// System.out.println("success 6");
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Related

.NET Core Mailkit Exception Too many recipients

I am trying to send an email to 250 of my users. This is my code:
using(var emailClient = new SmtpClient())
{
emailClient.Connect(Configuration.Server, Configuration.Port, Configuration.UseSSL);
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
emailClient.Authenticate(Configuration.UserName, Configuration.Password);
try
{
foreach(var item in EmailContents)
{
var message = new MimeMessage();
message.To.AddRange(item.Receiver.Select(x => new MailboxAddress(x)));
message.From.AddRange(item.Sender.Select(x => new MailboxAddress(x)));
message.Subject = item.Subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = item.Content
};
emailClient.Send(message);
}
}
catch(Exception e)
{
logger.LogError(e,ResilientLogger.ClassLibrary.Globals.LoggingGlobals.Error + "-" + e.Message);
}
emailClient.Disconnect(true);
}
However, for some reason I keep getting this error:
MailKit.Net.Smtp.SmtpCommandException: Too many recipients
at MailKit.Net.Smtp.SmtpClient.OnRecipientNotAccepted(MimeMessage message, MailboxAddress mailbox, SmtpResponse response)
at MailKit.Net.Smtp.SmtpClient.ProcessRcptToResponse(MimeMessage message, MailboxAddress mailbox, SmtpResponse response)
at MailKit.Net.Smtp.SmtpClient.RcptToAsync(FormatOptions options, MimeMessage message, MailboxAddress mailbox, Boolean doAsync, CancellationToken cancellationToken)
at MailKit.Net.Smtp.SmtpClient.SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IList`1 recipients, Boolean doAsync, CancellationToken cancellationToken, ITransferProgress progress)
at MailKit.Net.Smtp.SmtpClient.SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IList`1 recipients, Boolean doAsync, CancellationToken cancellationToken, ITransferProgress progress)
at MailKit.Net.Smtp.SmtpClient.Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
at ManagementStudio.Connect.Email.Email.BulkSend(EmailConfigurationViewModel Configuration, List`1 EmailContents)
Is this an IIS error or something I can fix in my code? I am using IIS8
The only way to fix this is to reduce the number of recipients that you specify in each message.
So instead of doing this:
foreach(var item in EmailContents)
{
var message = new MimeMessage();
message.To.AddRange(item.Receiver.Select(x => new MailboxAddress(x)));
message.From.AddRange(item.Sender.Select(x => new MailboxAddress(x)));
message.Subject = item.Subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = item.Content
};
emailClient.Send(message);
}
Do this:
foreach(var item in EmailContents)
{
var message = new MimeMessage();
message.From.AddRange(item.Sender.Select(x => new MailboxAddress(x)));
message.Subject = item.Subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = item.Content
};
int i = 0;
while (i < item.Recipients.Count) {
message.MessageId = MimeUtils.GenerateMessageId ();
message.To.Clear ();
for (int j = 0; j < 50 && i < item.Recipients.Count; j++)
message.To.Add (MailboxAddress.Parse (item.Recipients[i++]);
emailClient.Send(message);
}
}

sslstream won't work with SMTP protocol

The code i am using is simply for testing, here i test with gmail:
C# code:
private void button1_Click(object sender, EventArgs e)
{
string server = "smtp.gmail.com";
int port = 25;
client = new TcpClient();
client.Connect(server, port);
var stream = client.GetStream();
sslStream = new SslStream(stream);
sslStream.AuthenticateAsClient(server);
clearTextReader = new StreamReader(sslStream);
clearTextWriter = new StreamWriter(sslStream);
clearTextWriter.WriteLine("EHLO " + server);
clearTextWriter.Flush();
var response = clearTextReader.ReadLine();
Error(response);
}
But this errors with this error:
System.IO.IOException occurred
HResult=0x80131620
Message=The handshake failed due to an unexpected packet format.
Source=System
StackTrace:
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost)
When i try to do this on port 443, it works fine, however port 25, just errors all the time. I've tried everything but i can't find a solution. The certificate is valid, also when i try different servers it doesn't work.

Send email in specific time with Quartz

Hello i would like to ask your help concerning how to send email in quartz executor. That is my code
public class SchedulerJob implements Job{
#EJB
private ParticipationTaskDao participationTaskDao;
public void sendEmail() throws AddressException, MessagingException {
List<ParticipationTask> participantTasks=participationTaskDao.listParticipantTask();
for(ParticipationTask participantTask:participantTasks){
String subject="Task";
String message="You take part to the task "+participant.getTask().getName()+" from "+participant.getTask().getDateStart()+" to "+participant.getTask().getDateEnd()+". Description:"
+ participantTask.getTask().getDescription();
String receiver=participantTask.getUser().getEmail();
System.out.println("Email sent initialisation... ");
try {
final String username="mymail#gmail.com";
final String password="mypassword";
String host = "smtp.gmail.com";
String from = "mymail#gmail.com";
String pass = "mypassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(receiver);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(message);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
message.saveChanges();
Transport.send(message);
transport.close();
}catch(Exception ex){
System.out.println("<html><head></head><body>");
System.out.println("ERROR: " + ex);
System.out.println("</body></html>");
}
System.out.println(""Email sent successfully);
}
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
sendEmail();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
When i start my server, i don't see nothing but if i decide to test the below code all things runs correctly
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Quartz runs correctly");
}

How to fix corrupt byte[]-s in win socket

I have two win socket apps, server and client. The server app is at my virtual and client at host machine and the communication is OK. I am sending a ISO file (700MB) through that socket and I came across the error that received bytes are corrupt. When my file come to virtual machine, it has the original size, but the content is not OK. At the client side, I am using this code:
public class ProgramClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] msg;
try
{
IPAddress ipAd = IPAddress.Parse("192.168.137.71");
IPEndPoint remoteEP = new IPEndPoint(ipAd, 1234);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
Console.WriteLine("Client connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Sending file...");
msg = GetBinaryFile(#"C:\TCPIP\test_big.iso");
byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
int msgLength = BitConverter.ToInt32(msgLengthBytes, 0);
Console.WriteLine("int: {0}", msgLength);
Console.WriteLine("msgL size: {0}", msgLengthBytes.Length);
//join arrays, file size info, TCP header
byte[] result = new byte[msgLengthBytes.Length + msgLength];
Buffer.BlockCopy(msgLengthBytes, 0, result, 0, msgLengthBytes.Length);
Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);
//file extension info, TCP Header
byte extension = 2; //file extension code
byte[] newArray = new byte[result.Length + 1];
result.CopyTo(newArray, 1);
newArray[0] = extension;
result = newArray;
int bytesSent = sender.Send(result);
Console.WriteLine("result size: {0}", result.Length);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
private static byte[] GetBinaryFile(string filename)
{
byte[] bytes;
using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
return bytes;
}
public static void Main(String[] args)
{
StartClient();
}
}
At the server side I have the following code:
class ProgramServer
{
public static void Main(String[] args)
{
try
{
StartListening();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
while (true)
{
string outputPath = string.Empty;
outputPath = #"C:\output\output";
Console.WriteLine("Waiting for a connection...");
Socket handler = SocketInstance().Accept();
data = null;
//for the TCP header, get file extension
bytes = new byte[1];
int bytesReceivedExtension = handler.Receive(bytes);
string extension = GetExtension(bytes[0]);
outputPath = outputPath + extension;
//for the TCP header, get file size information
bytes = new byte[4];
int bytesReceived = handler.Receive(bytes);
int Lenght = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("msg length: " + Lenght);
int TotalReceivedBytes = 0;
while (TotalReceivedBytes < Lenght)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
TotalReceivedBytes = TotalReceivedBytes + bytesRec;
AppendAllBytes(outputPath, bytes);
}
Console.WriteLine("Bytes received total: " + TotalReceivedBytes);
Console.WriteLine(File.Exists(outputPath) ? "File received." : "File not received.");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
private static Socket SocketInstance()
{
IPAddress ipAd = IPAddress.Parse("192.168.137.71");
IPEndPoint localEndPoint = new IPEndPoint(ipAd, 1234);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
return listener;
}
public static void AppendAllBytes(string path, byte[] bytes)
{
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write(bytes, 0, bytes.Length);
}
}
public static string GetExtension(byte extOfFile)
{
switch (extOfFile)
{
case 0:
return ".txt";
case 1:
return ".png";
case 2:
return ".iso";
default:
return "";
}
}
}
So, how can I be sure that my byte[] is OK? Because when I open that ISO file at the received side, its content is not OK. IS there some alternative for any type of file to binary conversion?
Thanks.
The framing protocol you made up seems to work like this:
0 1 2 3 4 ... N
[L][L][L][L][D][...][D]
Where L represents an 32-bit integer (in which endianness?) indicating the lenght of the Data.
First, you're sending the wrong file length:
byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
Why do you subtract 3? You shouldn't. This causes the last 3 bytes to be chopped off the file.
Then when filling the message buffer, you start writing at byte 3, or the last byte of L:
Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);
This will cause the reader to interpret an incorrect data length. You should start at byte 4.
Third, when writing the file, you shouldn't append the entire buffer, but only the bytes that Receive() actually wrote in the buffer:
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
TotalReceivedBytes = TotalReceivedBytes + bytesRec;
AppendAllBytes(outputPath, bytes, bytesRec);
Then in that method:
public static void AppendAllBytes(string path, byte[] bytes, int bufferLength)
{
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write(bytes, 0, bufferLength);
}
}
And this is why you shouldn't write your own protocol and socket code if you don't know very well what you're doing. Leverage existing protocols and libraries instead.

if condition in asynchronous socket programming

How can I use if condition in asynchronous socket programming.
For example if client sends "hello" then server response is "hi" and if client send "how r u" then server send "i am fine".
I have this code and I am trying to do that, but it does not work.
Please tell where i need to change my code.
Thanks in Advance
Here is server code
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8888);
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
if (content == "hello")
{
Console.WriteLine(content);
Send(handler, content);
}
else if (content == "How r u")
{
Console.WriteLine(content);
Send2(handler, content);
}
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
data = "Hi";
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}
private static void Send2(Socket handler, String data)
{
data = "fine";
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
content == "How r u" and content == "hello" check the object equality by comparing there references. content and your const strings are not in the same memory (not the same objects).
To compare there content call content.compareTo("How r u")==0.
I solved it. I just have to put < eof > at the end of 'hello' like "hello< eof >" and same to how r u. Its work now.