Email Timeout C# - 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.

Related

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.

Multiple color fonts in one html email

mailItem.HTMLBody = "Dear IT Dept. You have received a new "+ comboBox3.Text + " priority task to complete from " + textBox1.Text + ". Please save the attached file and fit the task in to your schedule. Once completed please contact the " + textBox2.Text + " for comfirmation the task is completed to thier expectations. The Task is as follows: " + richTextBox1.Text + " Kind Regards, " + textBox1.Text + "";
I basically want to highlight the text/combo boxes or at least change their font color. Annoyingly you can't see the html code I used but it should be pretty obvious but I tried using the font color...with no luck. can't see where I'm going wrong
I can see that you try to put value of textBox2.txt. Your mistake is that wrote textBox2.txt as a string content. So you can achive this with using string.Format method.
You should to change it with this:
mailItem.HTMLBody = string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from ({0}) Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>", textBox2.Text);
Notice that textBox2.Text and {0} element.
Note: You also wrong with syntax of TextBox.Text property.
You need to have:
mailItem.HTMLBody = "<html><body>... from " + textBox2.Text + " Please ...";
instead of
mailItem.HTMLBody = "<html><body>... from (textBox2.txt) Please ...";
There is no HTMLBody property on the MailMessage class (assuming this is what you're using?).
It's just Body.
You would do something like this:
mailItem.Body = string.Format("<html><body><p>Dear {0}.</p>", comboBox3.Text);
Etc...
var mailItem= new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp server addess");
mailItem.From = new MailAddress("your_email_address#xyz.com");
mailItem.To.Add("it-department#???.co.uk");
mailItem.Subject = string.Format("You have a new task from {0}", comboBox3.Text);
mailItem.To = "";
mailItem.Body =string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from {0} Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to their expectations.</p>",textBox2.txt);
attachment = new System.Net.Mail.Attachment(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\????\IssueReport.txt");
mailItem.Attachments.Add(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\??\IssueReport.txt");
mailItem.IsBodyHtml = true;
// Optional Items based on your smtp server.
/* SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;*/
SmtpServer.Send(mailItem);
MessageBox.Show("mail Send");
Did you mean :
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from " + textBox2.Text + " Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
?
In your version, "textbox2.txt" will be manipulated as a string, it won't be "parsed".
In mine it's a control on your form and we put its text content in the mail.
Edit : you asked how to emphase the variable, here is a example :
Try something like
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from <strong>" + textBox2.Text + "</strong> Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
The "strong" tag around your variable will put the name in bold.

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.

smtpclient " failure sending mail"

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.

Mailto C# attachment syntax

How can I attach a file to this mailto string?
string mailto = "mailto:" + to + "&SUBJECT=" + subject + "?BODY=" + body +
"&Attachment=" + attachment;
This doesn't work; the file isn't attached.
Remove the quotes at the end of "attachment".
"mailto:" + to + "&SUBJECT=" + subject + "?BODY=" + body + "&Attachment=" + attachment
Where attachment has the attachment link.
Note: This will not work if the users dont have access to the attachment so you can try attaching and sending it through a c# code.
From what I saw on the web (and by trying it to), it is not always possible to do so. Some email client, and by some I mean lots of them, will not let you do this because it is considered a security hole. However, when it is accepted, the syntax provided by Shodan looks good.
Try this
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = string.Format("\"{0}\"", Process.GetProcessesByName("OUTLOOK")[0].Modules[0].FileName);
proc.StartInfo.Arguments = string.Format(" /c ipm.note /m {0} /a \"{1}\"", "someone#somewhere.com", #"c:\attachments\file.txt");
proc.Start();

Categories

Resources