smtpclient " failure sending mail" - c#

here is my code
for(int i = 0; i < number ; i++)
{
MailAddress to = new MailAddress(iMail.to);
MailAddress from = new MailAddress(iMail.from, iMail.displayName);
string body = iMail.body;
string subject = iMail.sub;
oMail = new MailMessage(from, to);
oMail.Subject = subject;
oMail.Body = body;
oMail.IsBodyHtml = true;
oMail.Priority = MailPriority.Normal;
oMail.Sender = from;
s = new SmtpClient(smtpServer);
if (s != null)
{
s.Send(oMail);
}
oMail.Dispose();
s = null;
}
this loops sends over 60,000 email. but my problem i am getting " failure sending mail" in some of the email some times 5000 and some time less then that rest of them gets delivered. and i have check all those error out email has valid email address. dont know what is the problem. i really need help in this.
Edit: This is my exception Trace
Error - Failure sending mail.; Inner
Ex - System.IO.IOException: Unable to
read data from the transport
connection: net_io_connectionclosed.
at
System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[]
buffer, Int32 offset, Int32 read,
Boolean readLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader
caller) at
System.Net.Mail.CheckCommand.Send(SmtpConnection
conn, String& response) at
System.Net.Mail.MailCommand.Send(SmtpConnection
conn, Byte[] command, String from) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress
sender, MailAddressCollection
recipients, String deliveryNotify,
SmtpFailedRecipientException&
exception)

Well, the "failure sending e-mail" should hopefully have a bit more detail. But there are a few things that could cause this.
Restrictions on the "From" address. If you are using different from addresses, some could be blocked by your SMTP service from being able to send.
Flood prevention on your SMTP service could be stopping the e-mails from going out.
Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.

apparently this problem got solved just by increasing queue size on my 3rd party smtp server.
but the answer by Nip sounds like it is fairly usefull too

I experienced the same issue when sending high volume email. Setting the deliveryMethod property to PickupDirectoryFromIis fixed it for me.
Also don't create a new SmtpClient everytime.

what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information
MSDN
Edit for the new information
Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.

For us, everything was fine, emails are very small and not a lot of them are sent and sudently it gave this error. It appeared that a technicien installed ASTARO which was preventing email to be sent. and we were getting this error so yes the error is a bit cryptic but I hope this could help others.

Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress out of the loop which you are using for sending mails. The fromaddress field is getting assigned again and again in the loop that is your problem.

Five years later (I hope this developer isn't still waiting for a fix to this..)
I had the same issue, caused by the same error: I was declaring the SmtpClient inside the loop.
The fix is simple - declare it once, outside the loop...
MailAddress mail = null;
SmtpClient client = new SmtpClient();
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Host = smtpAddress; // Enter your company's email server here!
for(int i = 0; i < number ; i++)
{
mail = new MailMessage(iMail.from, iMail.to);
mail.Subject = iMail.sub;
mail.Body = iMail.body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;
mail.Sender = from;
client.Send(mail);
}
mail.Dispose();
client.Dispose();

This error can appear when the web server can't access the mail server. Make sure the web server can reach the mail server, for instance pinging it.

Related

AT+CMGL="ALL" return OK only

I have 1 gsm 32 port with name is xr21v1414 USB UART
I have tested another AT COMMAND which works fine like
AT
USSD
but if i use COMMAND :
serialPort.WriteLine("AT" + System.Environment.NewLine);
Thread.Sleep(200);
serialPort.WriteLine("AT+CMGF=1" + System.Environment.NewLine);
Thread.Sleep(200);
serialPort.WriteLine("AT+CMGL=\"ALL\"" + System.Environment.NewLine);
Thread.Sleep(200);
responded with
serialPort.ReadExisting();
is empty (OK only)
AT
OK
AT+CMGF=1
OK
AT+CMGL="ALL"
OK
But if I switch to another gsm, Command work fine. I have list SMS.
This is my setting :
SerialPort serialPort = new SerialPort();
serialPort.PortName = m.ToString();
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.StopBits = StopBits.One;
serialPort.Parity = Parity.None;
serialPort.ReadTimeout = 20000;
serialPort.WriteTimeout = 20000;
serialPort.WriteBufferSize = 1024;
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
How could i resolve the problem ,please ?
I am quite sure that the OK response you get is because you have aborted the current command line by using Thread.Sleep(200) instead of reading and parsing the response you get back from the modem, waiting for the Final Result Code before sending the next command.
The first linked answer above is to a question whose code which is slightly worse because it does not even have a sleep, but even having one is utterly wrong. Just as you would not write a HTTP client that ignores the responses a HTTP server send it, you should not write a AT command program that ignores the responses the modems sends it.
TL;DR You MUST change your code to read and parse every single response line that the modem sends you, waiting for the Final Result Code before sending the next command. See the linked answers for more details.

Email Program issues

I work for a company and I was asked to write some script that would do a robocopy of a destination, then email the log with the subject being either failed or success. After a quite a bit of research I could not figure out why my program keeps breaking, and it's breaking in an odd way as well.
The script consists of a batch script and a c# application to send the email.
RobocopyScript.cmd
#echo off
set robocopydestination=\\[computer]\guest\TESTFOLDER\
set robocopysource=C:\Users\[username]\Script
set robocopylogoutput=log.log
set mailfrom=[email address]
set mailto=[email address]
set successsubject=Robocopy Success
set successbody=Robocopy successfully completed its backup.
set failuresubject=Robocopy Failure
set failurebody=Robocopy failed to complete its backup
set networkcredentialusername=[email address]
set networkcredentialpassword=[password]
set logfile=log.log
robocopy %robocopysource% %robocopydestination% /e /z /tee /log:%robocopylogoutput%
if errorlevel 1 goto success
if errorlevel 0 goto success
goto fail
:fail
EmailProgram.exe %mailfrom% %mailto% %failuresubject% %failurebody% %networkcredentialusername% %networkcredentialpassword% %logfile%
exit
:success
EmailProgram.exe %mailfrom% %mailto% %successsubject% %successbody% %networkcredentialusername% %networkcredentialpassword% %logfile%
exit
EmailProgram.csx
using System;
using System.Net.Mail;
namespace EmailProgram
{
class MainClass
{
public static void Main(string[] args)
{ // from To Subject Body
MailMessage mail = new MailMessage(args[0], args[1], args[2], args[3]);
SmtpClient client = new SmtpClient();
//set up the smtp client
client.Port = 25;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com"; //ncu ncp
client.Credentials = new System.Net.NetworkCredential(args[4], args[5]);
//add 4 lines of space between the body message and the log information for readability
mail.Body += "\r\n\r\n\r\n\r\n----------------\r\nLOG START:\r\n----------------";
//break up the log file into its lines, then write the lines to the email message body
//log file path
string[] logLines = System.IO.File.ReadAllLines(args[6]);
foreach(string s in logLines)
{
mail.Body += s;
}
//send the email, if the email fails to send it simply will close this application
try
{
client.Send(mail);
}
catch(Exception e)
{
System.Console.WriteLine(e);
}
}
}
}
On running the batch script, robocopy finishes successfully, then as it tries to run EmailProgram.exe it gives me:
Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'C:\Users\[username]\Script\CompleteProjects\RobocopyEmail\completed'.
I'm definitely no expert, but I see nowhere in my code that calls the path that the exception gives. Could someone please help me figure this out because i'm stumped after several hours of trying to figure this out. Thanks :)
There are spaces in the variables successsubject etc.
When you call EmailProgram.exe %mailfrom% %mailto% %successsubject% %successbody% ..., you really emit the call
EmailProgram.exe apa#bepa.com qux#foo.bar Robocopy Success Robocopy successfully completed its backup...
So completed becomes args[6] in the emailer.
Try
EmailProgram.exe "%mailfrom%" "%mailto%" "%successsubject%" "%successbody%" ...
instead.

Microsoft.Office.Interop.Outlook Confirmation email doesn't work when Outlook is open

I am trying to send a confirmation email when a user submits a form. I had privlage problems with smtp so I am trying to do it through Outlook. The code works fine enter link description here when Outlook isn't open but just hangs when it is. Any ideas how to fix this or ways around it?
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "Hello, Jawed your message body will go here!!";
//Subject line
oMsg.Subject = "Your Subject will go here.";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("email#address.com");
oRecip.Resolve();
// Send.
((Outlook._MailItem)oMsg).Send();
// Clean up.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oMsg);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRecip);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRecips);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oApp);
}//end of try block
catch (Exception ex)
{
}//end of catch
Try checking to see if there is an instance of Outlook already open, if there is one use it to send the mail. If not then create the new instance.
(Untested) this should get you started:
Outlook.Application oApp;
try {
oApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
}
catch () {
oApp = new Outlook.Application();
}
// use oApp to send the stuff, it will either be the existing instance or a new instance

Email Timeout C#

I have a program that sends an email with attachments, it works fine at home with a good internet connection but times out when I use a slower connection.
Does anyone know if I can extend the time out so it will send over a slower network.
The code I use is
Cursor.Current = Cursors.WaitCursor;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(FilePaths.Default.SquadronEmailAddress);
mail.To.Add(FilePaths.Default.Email);
mail.Subject = FilePaths.Default.SquadronNumber + " Gliding Training Return";
mail.Body = "Please find attached todays Training Return from " + FilePaths.Default.SquadronNumber +
". Please do not reply to this email address as its unmonitored. " +
"If you have any questions or require further information please contact the Adj on adj.644vgs#aircadets.org";
mail.Attachments.Add(new Attachment(FilePaths.Default.GlidingTrainingReturnFolder + ("\\Gliding Training Return" + date.ToString("dd-MMM-yyyy") + ".pdf")));
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(FilePaths.Default.SquadronEmailAddress, FilePaths.Default.DatabasePassword);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("Email Sent");
Use the timeout property of the SmtpClient class
SmtpServer.timeout = 200000 ; //change it as needed
specifies the time-out value in milliseconds. The default value is 100,000 (100 seconds).
By the way calling SmtpServer a variable that is actually a SmtpClient is very bad practice
For more details see
this link
You can change the timeout by modifying the SmtpClient.Timeout property. It defaults to 100 seconds, which is already a lot, so if you are really exceeding that, you might want to look for a different solution instead. You could for example upload the attachment somewhere and send a link instead—the recipient will thank you too.

Open the default mail manager containing an attached file (Windows)

I need to open an new email with an attachment via the default mail manager (without SMTP code)
I use:
System.Diagnostics.Process.Start(String.Format("mailto:{0}", txtEmail.Text))
Is it possible to add an attachment too?
I could try this
http://www.codeproject.com/Articles/17561/Programmatically-adding-attachments-to-emails-in-C
but I should understand that there is always a Microsoft Outlook need to the client computer...
It's impossible ?!
ive provided a detailed way to do it using System.Net.Mail namespace;
private void button1_Click(object sender, EventArgs e)
{
SmtpClient smtpserver = new SmtpClient();
smtpserver.Credentials = new NetworkCredential("email#domain", "passphrase");
smtpserver.Port = 587;
smtpserver.Host = "smtp.live.com";
smtpserver.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("email#domain");
mail.To.Add("recipient#domian");
mail.Subject = "testing";
string pathTOAttachment;
string _Attachment = pathToAttachment;
Attachment oAttch = new Attachment(_Attachment);
mail.Attachments.Add(oAttch);
mail.Body = "message body";
ThreadPool.QueueUserWorkItem(delegate
{
try
{
smtpserver.Send(mail);
}
//you can get more specific in here
catch
{
MessageBox.Show("failure sending message");
}
});
}
Noteworthy (not taken into consideration in this code sample):
some isp may impose size limitation on attachment, some make sure you check it before attempting to send the email.
smtp hosts/port may vary, the most efficient way is to check against a regularly updated database, or let the user set them himself.
the threading part is all about UI responsiveness, but, if the user close the main app window with the mail still sending, it'll be preempted.

Categories

Resources