SMTPClient takes too long to send asp.net email - c#

I have here a bunch of code regarding SMTPClient Send mail:
public void SendEmailToCustomer(ReservationDetails reservationDetails, string reason, string cardtype) {
MailMessage msg = new MailMessage(ConfigurationManager.AppSettings["Email.Sender"], reservationDetails.Email);
msg.Subject = this.Subject;
msg.Body = this.Body.Replace("[InvoiceNumber]", reservationDetails.Invoice)
.Replace("[GuestName]", reservationDetails.Name)
.Replace("[GuestTelephone]", reservationDetails.Telephone)
.Replace("[GuestEmail]", reservationDetails.Email)
.Replace("[GuestAddress]", reservationDetails.Address)
.Replace("[GuestCompany]", reservationDetails.CompanyName)
.Replace("[GuestCompanyAddress]", reservationDetails.CompanyAddress)
.Replace("[GuestCompanyNumber]", reservationDetails.CompanyNumber)
.Replace("[OtherRemarks]", reservationDetails.Other)
.Replace("[TransferDescription]", reservationDetails.TransferDescription)
.Replace("[FlightArrivalDate]", reservationDetails.ArrivalDate)
.Replace("[ETA]", reservationDetails.ETA)
.Replace("[FlightArrival]", reservationDetails.FlightArrival)
.Replace("[FlightDepartureDate]", reservationDetails.DepartureDate)
.Replace("[ETD]", reservationDetails.ETD)
.Replace("[FlightDeparture]", reservationDetails.FlightDeparture)
.Replace("[NoOfNights]", reservationDetails.NoOfNights)
.Replace("[CheckIn]", reservationDetails.CheckIn)
.Replace("[CheckOut]", reservationDetails.CheckOut)
.Replace("[RoomName]", reservationDetails.RoomName)
.Replace("[Qty]", reservationDetails.Qty)
.Replace("[RoomAmount]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.RoomAmount)))
.Replace("[RateRoom]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.RateRoom)))
.Replace("[NumExtra]", Convert.ToString(reservationDetails.NumExtra))
.Replace("[ExtraAmount]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.ExtraAmount)))
.Replace("[RateExtra]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.RateExtra)))
.Replace("[RTTQty]", Convert.ToString(reservationDetails.RTTQty))
.Replace("[RTT]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.RTT)))
.Replace("[RTTAmount]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.RTTAmount)))
.Replace("[TotalAmount]", String.Format("{0:N}", Convert.ToDecimal(reservationDetails.TotalAmount)))
.Replace("[ModePay]", reservationDetails.ModePayment)
.Replace("[Reason]", "Reason: " + reason)
.Replace("[CardType]", cardtype)
;
msg.CC.Add(this.AddressCC);
msg.Bcc.Add(this.AddressBCC);
msg.IsBodyHtml = true;
try {
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["Smtp.Client"]);
client.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Smtp.Credentials.Username"], ConfigurationManager.AppSettings["Smtp.Credentials.Password"]);
client.Send(msg);
} catch (Exception ex) {
//Do nothing
//throw new Exception("Couldn't send email: <p>" + ex.Message);
} finally {
msg.Dispose();
}
}
It takes too long to send an email (approx. 5 seconds).
I also disposed MailMessage.
What could be the possible cause of the email delay. And how can I resolve the issue?
Many thanks!! :D

Related

Outlook VSTO - mailItem body problems

I'm having a problem with email sending in C#.
I'm working on an add-in and everything is going well. I can send my mails, like i want, but not "two times in a row".
For example, my add-in open a Form and after the user action an email is sent.
When the mail is sent, the form is closed and that's okay.
But some time, i need to send two separate emails and the body of second email is always empty. By the way, i fill the "body" of my mails with Word (Microsoft.Office.Interop.Word) to have some formatted text.
If I use the .Body property there is no problem.
Now, I'm wondering if it's not the fault of "Word" because the email part is working but only the body is empty.
I tried to send my mails in the inverse order to see if it's occurs always with the second mail and i was right. It's not about the email or his content but more about being the second sent.
It may be some things which haven't been released yet(not properly released objects) or something like that but i'm doing already it.
That's how i'm doing..
Outlook.MailItem mailItem = (Outlook.MailItem)new Outlook.Application().CreateItem(Outlook.OlItemType.olMailItem);
try
{
mailItem.CC = currentUserExchange.PrimarySmtpAddress;
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Subject = "XXX";
mailItem.To = finalRecipients;
fillBody(mailItem, mailBody);
mailItem.Send();
}
catch (Exception ex) { }
finally
{
releaseObject(mailItem);
}
if (moderatorPin != String.Empty)
{
Outlook.MailItem mailItemSecurity = (Outlook.MailItem)new Outlook.Application().CreateItem(Outlook.OlItemType.olMailItem);
try
{
mailItemSecurity.Importance = Outlook.OlImportance.olImportanceHigh;
mailItemSecurity.Subject = "XXX";
mailItemSecurity.To = currentUserExchange.PrimarySmtpAddress;
fillBody(mailItemSecurity, mailBodySecure);
mailItemSecurity.Send();
}
catch (Exception ex) { MessageBox.Show("error : " + ex.Message); }
finally
{
releaseObject(mailItemSecurity);
}
}
and :
private void fillBody(Outlook.MailItem mailItem, String bodyMail)
{
Word.Document document = mailItem.GetInspector.WordEditor;
Word.Range rng = document.Paragraphs[1].Range;
try
{
document.Paragraphs[1].LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
rng.set_Style(Word.WdBuiltinStyle.wdStyleHtmlKbd);
rng.Font.Color = (Word.WdColor)(fontColor.R + 0x100 * fontColor.G + 0x10000 * fontColor.B);
rng.Text = bodyMail;
rng.Select();
}
catch (Exception ex)
{
MessageBox.Show("XXX");
}
finally
{
releaseObject(rng);
releaseObject(document);
}
}

Object variable or With block variable not set while sending attachment in email in asp.net

I need to send attachment with email. I used following code which gives below exceptions.
System.NullReferenceException: Object variable or With block variable
not set. at
Microsoft.VisualBasic.CompilerServices.Symbols.Container..ctor(Object
Instance) at
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object
Instance, Type Type, String MemberName, Object[] Arguments, String[]
ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) at
dynamicPage.makeCustom_Click(Object sender, EventArgs e)
try {
generateRequestID();
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.To.Add("email.text");
mail.From = new MailAddress(personEmail.Text);
mail.Subject = "IDFC Bank BrandStore Product Customization Request";
mail.Body = "Request ID : " + Session["requestID"].ToString + "<br>Name : " + personName.Text + "<br>Contact : " + personContact.Text + "<br>Email : " + personEmail.Text + "<br>Department : " + Department.Text + "<br>Quantity : " + quantity.Text + "<br>Description : " + customDescription.Text + "<br>Timeline : " + customTimeline.Text + "<br>Product Link : " + Request.Url.AbsoluteUri + "";
if (artworkContainer.HasFile) {
string FileName = Path.GetFileName(artworkContainer.PostedFile.FileName);
mail.Attachments.Add(new Attachment(artworkContainer.PostedFile.InputStream, FileName));
}
mail.IsBodyHtml = true;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("you#yourdomain.com", "mypassword");
SmtpServer.Host = "relay-hosting.secureserver.net";
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
Response.Redirect("/customization-request-sent");
} catch (Exception ex) {
Response.Write(ex);
}

How to export Crystal report to PDF and email in c#

I am trying to convert a crystal report to pdf as I need to mail it. So I looked tried few steps but to no avail.
I tried:
RPTBanQoute printbanqoute = new RPTBanQoute();
printbanqoute.SetDataSource(ds);
printbanqoute.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, #"E:\ASD.pdf");
In this nothing happens.
Then I tried :
try
{
// Export the Report to Response stream in PDF format and file name Customers
//printbanqoute.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Customers");
printbanqoute.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Quotation");
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ex = null;
}
Getting an error on Response as The name 'Response' does not exist in the current context
I tried using Server.Mappath but intellisense doesnt show Mappath. I used System.Web
Heres how I am populating data onto Crystal reprt :
MySqlCommand cmd = new MySqlCommand("SELECT tb.BookingID, BookingDate, Event, EventDate, EventTime, Pax, Service, ServiceTime, f.FoodMenu, f.ExtraItem FROM tblBookingDetails tb, tblMenu f WHERE tb.BookingID = #bookid AND tb.BookingID = f.BookingID", con.con);
cmd.Parameters.AddWithValue("#bookid", BLDashboard.bookingID);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet1 ds = new DataSet1();
adapter.Fill(ds, "BookingDetails");
if (ds.Tables["BookingDetails"].Rows.Count == 0)
{
MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
RPTBanQoute printbanqoute = new RPTBanQoute();
printbanqoute.SetDataSource(ds);
I am also passing parameter values to this Crystal report.
So please advice how to achieve converting to PDF and email
Also I googled further and tried these codes :
cryRpt = new ReportDocument();
cryRpt.Load("E:\\Office\\Clients\\Bombay Restaurant\\Banquet New - MySql\\Banquet New\\RPTBanQoute.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
try
{
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.pdf";
CrExportOptions = cryRpt.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
But this gave me exception :
I am able to solve my issue. I was writing all codes in crystalviewer1_Load event ie; exporting and email as well as populating data to crystal report. So I had to create a Button Email to export and email.
Heres my code to export and email, Button1 is the email button on crystalviewer:
private void button1_Click(object sender, EventArgs e)
{
try
{
billprint.ExportToDisk(ExportFormatType.PortableDocFormat, "E:\\" + filename);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
try
{
MailMessage mm = new MailMessage();
string toemail = BLDashboard.email;
string custnm = BLDashboard.custname;
mm.From = new MailAddress("operations#kaem.in", "Kashif Ahhmed");
mm.To.Add(new MailAddress(toemail, custnm));
mm.IsBodyHtml = true;
string name = BLDashboard.custname;
mm.Subject = "Bill from Indian Restaurant";
//mm.Body = "Testing Crsytel Report Attachment send via Email";
String Body = "<div>Hello " + name + ",<br> Thank you for considersing us for your next Party/Event, here is the Bill for the Party/Event.<br> If any queries you can reach us at 6096464445. <br> Thank You</div>";
mm.Body = Body;
//mm.Attachments.Add(new Attachment(rpt.ExportToStream(ExportFormatType.PortableDocFormat), fileName));
mm.Attachments.Add(new Attachment("E:\\" + filename));
SmtpClient sc = new SmtpClient("smtp.kaem.in");
sc.Credentials = new NetworkCredential("emailadd", "*********");
sc.Send(mm);
// MailMessage msg = mm.CreateMailMessage("mr.markwhite1#gmail.com", replacements, Body, new System.Web.UI.Control());
MessageBox.Show("Email successfully sent to " + toemail);
}
catch (Exception e1)
{
MessageBox.Show("Unable to send email to mr.markwhite1#gmail.com due to following error:\n\n" + e1.Message, "Email send error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//{
// this.SendEmail(emailId, subject, body, rpt, fileName);
//}
}
}

How can i send email one after one in a row?

In Form1 in the backgroundworkerdowork event I did:
se.SendPhotos(photofilesDir + "\\" + "photofiles.zip");
se.SendPhotos(photofilesDir1 + "\\" + "photofiles.zip");
se.SendPhotos(photofilesDir2 + "\\" + "photofiles.zip");
se.SendPhotos(photofilesDir3 + "\\" + "photofiles.zip");
In the se class SendEmail I did:
public void SendPhotos(string fileNameToSend)
{
try
{
MailAddress from = new MailAddress("test#gmail.com", "User " + (char)0xD8 + " Name",
System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("test#test");
photosmessage = new MailMessage(from, to);
photosmessage.Body = "Please check the log file attachment I have some bugs.";
string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
photosmessage.Body += Environment.NewLine + someArrows;
photosmessage.BodyEncoding = System.Text.Encoding.UTF8;
photosmessage.Subject = "Log File For Checking Bugs" + someArrows;
photosmessage.SubjectEncoding = System.Text.Encoding.UTF8;
Attachment myAttachment = new Attachment(fileNameToSend, MediaTypeNames.Application.Octet);
photosmessage.Attachments.Add(myAttachment);
SmtpClient photossend = new SmtpClient("smtp.gmail.com", 587);
photossend.SendCompleted += new SendCompletedEventHandler(photossend_SendCompleted);
photossend.EnableSsl = true;
photossend.Timeout = 10000;
photossend.DeliveryMethod = SmtpDeliveryMethod.Network;
photossend.UseDefaultCredentials = false;
photossend.Credentials = new NetworkCredential("usern", "userpass");
string userState = "test message1";
photossend.SendAsync(photosmessage, userState);
SendLogFile.Enabled = false;
fname = fileNameToSend;
}
catch (Exception errors)
{
Logger.Write("Error sending message :" + errors);
}
}
private void photossend_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
photosmessage.Dispose();
if (fname == #"C:\Users\Simbalip\AppData\Local\outputphotos\photosfiles3" + "\\" + "photofiles.zip")
{
photossendended = true;
}
}
The problem in the backgroundworkerdowork it never send the last one photofilesDir3.
I used a breakpoint and its getting to : photossendended = true;
But in my email im getting only 3 files sent for me and not 4.
When I used a breakpoint on the backgroundworker and did F11 I saw that its doing the 4 sendings one after one without waiting .
Each time the photofiles.zip have different files inside.
Now I check did a breakpoint on the line:
if (fname == #"C:\Users\Simbalip\AppData\Local\outputphotos\photosfiles3" + "\\" + "photofiles.zip")
And when it get there its all the time true it does ==
fname never C:\Users\Simbalip\AppData\Local\outputphotos\photosfiles2 or 1 or photosfiles
But in the end im getting 3 different photofiles.zip files each contain different files but one of the files never sent.
Myabe I need to make somehow that when it send email it will somehow untill the first one is sent then send the next one like in Process there is WaitForExit() so maybe something like that with the emails ?
The documentation for SmtpClient alludes to the fact that it doesn't support parallel operations.
If there is an e-mail transmission in progress and you call SendAsync or Send again, you will receive an InvalidOperationException.
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
I would recommend not sending the next email until the SendCompleted event has been raised. This means a drastic change in your code (where each call to SendPhotos really just adds something to a collection of pending send mail operations that your process in the background)

C# Sending Email - Sanity check

Sanity check of an email implementation please :-) Anything obvious I've missed?
string supplierOfThisMaterialEmailAddress = "davexxx#gmail.com"; // TODO
string htmlBodyIncludingReplacements = "<html><head><title>E-mail</title></head><body><div>. There has been a request on the hello.co.nz website for: " + txtMaterialDescription.Text +
"<br />Full Name: <b>" + fullName + "</b><br />" +
etc..";
string textOnlyBodyIncludingReplacements = "E-mail. There has been a request on the freematerials.co.nz website for: " + txtMaterialDescription.Text +
"Full Name: " + fullName +
"etc..";
string subject = "Someone has contacted you";
CustomMailer mailer = new CustomMailer();
string result = mailer.SendEmail(subject, htmlBodyIncludingReplacements, supplierOfThisMaterialEmailAddress, textOnlyBodyIncludingReplacements);
if (result != null)
lblMessage.Text = result;
else
lblMessage.Text = "Thank you - email has been sent";
And the class:
public class CustomMailer
{
public string SendEmail(string subject, string htmlBodyIncludingReplacements, string emailTo, string textOnlyBodyIncludingReplacements)
{
try
{
MailAddress sender = new MailAddress("dave#hello.co.nz", "Dave Mateer");
emailTo = "dave#hello.co.nz"; // testing
MailAddress recipient = new MailAddress(emailTo, null);
MailMessage message = new MailMessage(sender, recipient);
message.Subject = subject;
AlternateView textView = AlternateView.CreateAlternateViewFromString(textOnlyBodyIncludingReplacements, null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBodyIncludingReplacements, null, MediaTypeNames.Text.Html);
message.AlternateViews.Add(textView);
message.AlternateViews.Add(htmlView);
SmtpClient client = new SmtpClient();
client.Send(message);
}
catch (Exception ex)
{
throw new Exception();
}
return null;
}
}
At first glance, catching a general Exception object and throwing a new one is going to have the net effect of eating any exceptions thrown by SendEmail.
The rest looks okay.
You should change the
catch (Exception ex)
{
throw new Exception();
}
to :
catch (Exception ex)
{
throw;
}
because otherwise you lose all the data that came with the original excepion that was thrown

Categories

Resources