Sending email with attachments using loop to different email address using C# - c#

Hellow, I`ve tried to create a pdf files and send them at the same time in a loop to different email address, but it seems the first created file doesnt close to allow the next one to be created, i use the same name (overwriting the file).
here is the code for attaching the email
private void sendEmail(string email)
{
sendInfo = new Label();
sendInfo.Font = new Font("Calibri", 11);
sendInfo.AutoSize = true;
MailMessage mail = new MailMessage("ikwabe04#gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante.");
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("ikwabe04#gmail.com", "mikunjoyamwili");
client.EnableSsl = true;
Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf");
file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
mail.Attachments.Add(file);
try
{
client.Send(mail);
Login.RecordUserActivity("Sent the Salary Slip to " + email);
sendInfo.ForeColor = Color.LightGreen;
sendInfo.Text = "Email sent to: " + email + " (" + DateTime.Now.ToLongTimeString() + ")";
information.Controls.Add(sendInfo);
}
catch
{
sendInfo.ForeColor = Color.Orange;
sendInfo.Text = "Email NOT sent to: " + email + " ("+DateTime.Now.ToLongTimeString()+")";
information.Controls.Add(sendInfo);
}
}
here code to create a pdf
using (FileStream file = new FileStream("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf", FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfDoc, file);
pdfDoc.Open();
pdfDoc.Add(table);
pdfDoc.Add(slp);
pdfDoc.Add(Separator);
pdfDoc.Add(table1);
pdfDoc.Add(Separator);
pdfDoc.Add(Tsh);
pdfDoc.Add(incomeTitle);
pdfDoc.Add(incomeTable);
pdfDoc.Add(totaInc);
pdfDoc.Add(taxDeductionTitle);
pdfDoc.Add(taxDeduction);
pdfDoc.Add(otherDeductionTitle);
pdfDoc.Add(OtherDeduction);
pdfDoc.Add(totaDeduc);
pdfDoc.Close();
file.Close();
}
here is the code for sending email
for (int i = 0; i< table.Rows.Count;i++)
{
PreapareSalarySlip(table.Rows[i][2].ToString(),
table.Rows[i][3].ToString(),
table.Rows[i][5].ToString(),
table.Rows[i][37].ToString()
);
sendEmail(table.Rows[i][38].ToString());
}
here is the Error occured
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\Shadrack Ikwabe\AppData\Roaming\SEC Payroll\Receipts\receipt.pdf' because it is being used by another process.

It isn't the PDF creation process that is locking the file. It's the attachment. The Attachment class locks the file and doesn't release the lock until it is disposed. You're getting the exception because you're trying to attach the same file to two different emails without releasing the lock by disposing of the attachment.
SmtpClient and MailMessage are also disposable. Disposing of the MailMessage is sufficient; when it is disposed, it also disposes its attachments. However, I consider it better to make it explicit.
You should be disposing of them properly using a using:
using (MailMessage mail = new MailMessage("ikwabe04#gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante."))
using (SmtpClient client = new SmtpClient("smtp.gmail.com"))
using (Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf"))
{
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("ikwabe04#gmail.com", "mikunjoyamwili");
client.EnableSsl = true;
file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
mail.Attachments.Add(file);
try
{
client.Send(mail);
Login.RecordUserActivity("Sent the Salary Slip to " + email);
sendInfo.ForeColor = Color.LightGreen;
sendInfo.Text = "Email sent to: " + email + " (" + DateTime.Now.ToLongTimeString() + ")";
information.Controls.Add(sendInfo);
}
catch
{
sendInfo.ForeColor = Color.Orange;
sendInfo.Text = "Email NOT sent to: " + email + " ("+DateTime.Now.ToLongTimeString()+")";
information.Controls.Add(sendInfo);
}
}

Related

I can send smtp message on a localHost But i cant send it on a Live WebSite

im using Asp.net And I have the Umbraco Cms on my project
i implemented The Send message using razor syntax
im submitting a from to the following razor syntax
#{ if (IsPost)
{
string name = Request["name"];
string email = Request["email"];
string phone = Request["phone"];
string city = Request["city"];
string note = Request["note"];
NetworkCredential basicCredential =new NetworkCredential("*****#gmail.com", "******");
MailMessage mail = new MailMessage();
//var from = new MailAddress(Email.Text);
mail.From = new MailAddress(email);
mail.To.Add("tupacmuhammad5#gmail.com");
mail.Subject = "Torcan WebSite Contact Us";
mail.IsBodyHtml = false;
mail.Body = "You just got a contact email:\n" +
"Name: " + name + "\n"
+ "Email: " + email + "\n"
+ "TelePhone: " + phone + "\n"
+ "Address: " + city + "\n"
+ "Message: " + note + "\n";
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = basicCredential;
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
finally
{
smtp.Dispose();
}
}
}
it works perfect on My localHost But on a live server its thorws a runtime error "after i remove the try catch "
i cant find out what seems to be problem
im writing this code in umbraco backoffice tamplate i have the server on onther country and i dont have access to it any help ? please ?
The Problem was that the Server is located in Germany so when the server tries to open my Gmail account. its a different country and never seen action from there.
so all i had to do is to open my gmail via remote access on the server machine via a browser and confirmed it was me then every thing worked perfectly.

Send a mail from web server using asp.net? Not working in Godaddy webserver

I have a website, there is a Contact Us tab. User have to fill the form and when click the button I should get a mail from user.
It's working fine when I am running from localhost. But the same code it is not running in Godaddy webserver. This is my code
try
{
MailMessage mailMessage = new MailMessage("From#gmail.com", "To#mydomain.com");
mailMessage.Subject = txtSubject.Text;
string msg = "#Sender Name: " + txtUserName.Text + "#Sender Email ID: " + txtUserEmailId.Text + "#Company Name: " + txtCompanyName.Text + "#Mobile No: " + txtMobileNo.Text + "#Office Telephone No: " + txtOfficeTelephoneNo.Text + "#Office Fax No: " + txtOfficeFaxNo.Text + "#City: " + txtCity.Text + "#Sender Message: " + txtMessage.Text;
string newMsg = msg.Replace("#", "\n");
mailMessage.Body = newMsg;
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "From#gmail.com",
Password = "Password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
catch (Exception ee)
{
Response.Write(ee.Message);
}

how to solve non-local email authentication?

in 3.5 .Net Framework i have a problem to sending an email on server.
Code-
MailMessage message = new MailMessage();
message.From=new MailAddress("CMC Enquiry" + "<my1#domain.in>");
message.To.Add(new MailAddress("vishalpatel8086#gmail.com"));
message.CC.Add(new MailAddress("varun_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
// try
// {
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
// }
// catch
// {
// Label5.Text = "Low Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
// }
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
This code is working my other web hosting server with my different website but is not working with new web site . A error is being occured like -
Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.
Error Is -
Line 83: SMTPServer.Send(message);
Source File: c:\inetpub\vhosts\cmcent.in\httpdocs\enquiry.aspx.cs
Line: 83
Your SmtpClient code needs to be revised as follow:
//Set your smtp client settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.yourdomain.com"; //set with your smtp server
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail#yourdomain.com", "fromEmailPassword");
smtp.Timeout = 20000;
}
// Now send your email with this smtp
smtp.Send(message);
Optionally you can also try to enable/disable ssl & changing the port.

Hooking into SMTP client events

Intro: I am supporting a piece of code that sends a welcome/confirm mail upon successful registration to a site.
The SMTP client times out before sending can complete. According to our Ops department, I am using the correct credentials and SMTP server IP address.
What I want to do is hook into any handshaking, connection, sending, etc events so that I can figure out exactly why the process times out. I've set Server.ScriptTimeOut to 500 seconds on that page, so it can't just be a busy server problem.
My question is this: what events can I handle during this process. The only one I see exposed in SMTPClient is SendCompleted. But I imagine there must be a way to get access to something more low-level?
For reference, here's the code:
//Create and send email
MailMessage mm = new MailMessage();
try
{
mm.From = new MailAddress("admin#site.com");
mm.To.Add(new MailAddress(Recipient));
mm.Subject = Subject;
mm.Body = MailBody;
mm.IsBodyHtml = true;
var c = new NetworkCredential("admin#site.com", "YeOlePassword");
SmtpClient smtp = new SmtpClient("127.0.0.1");//not really, just hiding our SMTP IP from StackOverflow
smtp.UseDefaultCredentials = false;
smtp.Credentials = c;
smtp.Send(mm);
}
catch (Exception x)
{
DateTime CurrentDateTime = DateTime.Now;
String appDateTime = CurrentDateTime.ToString();
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + x.Message;
StreamWriter streamwriter = new StreamWriter(File.Open(MapPath("~/TransactionLog.txt"), FileMode.Append, FileAccess.Write, FileShare.Write));
//Append to file
streamwriter.WriteLine(transactionLogEntry);
//Close file
streamwriter.Close();
}
The error that's logged is simply that a timeout occured while sending a mail to the supplied email address.
I use this to get the buried SMTP messages out.
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + GetFullErrorMessage(x);
.
.
.
private string GetFullErrorMessage(Exception e)
{
string strErrorMessage = "";
Exception excpCurrentException = e;
while (excpCurrentException != null)
{
strErrorMessage += "\"" + excpCurrentException.Message + "\"";
excpCurrentException = excpCurrentException.InnerException;
if (excpCurrentException != null)
{
strErrorMessage += "->";
}
}
strErrorMessage = strErrorMessage.Replace("\n", "");
return strErrorMessage;
}
In my experience, from what you are describing it is related to your SMTP port being blocked by and ISP or your server/web host. Good luck!

I'm having problems with SMTP Authentication in C#

I have an MVC 3 app and everything I try on my new hosting provider ends up throwing this exception:
Server Error in '/' Application.
Mailbox unavailable. The server response was: Authentication is required for relay
I tried using the code from
How can I make SMTP authenticated in C#
which has many up votes, but I still get the exception.
My host has the typical panels that let me create mail accounts. I'm not sure about creating NetworkCredentials, what do I use as the User Name and password? What I've been using is the email address and the password for the email account.
Here's my code:
public static void sendMail(Joiner request) {
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("garbage#stopthedumpcoalition.org", "REDACTED");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("garbage#stopthedumpcoalition.org");
smtpClient.Host = "mail.stopthedumpcoalition.org";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "Join the Coalition request from - " + request.FirstName + " " + request.LastName;
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "Name: " + request.FirstName + " " + request.LastName + "<br>"
+ "EMail: " + request.Email + "<br>"
+ "Wants to Volunteer: " + request.Volunteer.ToString() + "<br>"
+ "Organization: " + request.Organization + "<br>"
+ "Wants to become a Partner: " + request.Partner.ToString() + "<br>"
+ "Comments: " + request.Comments;
message.To.Add("nivram509#gmail.com");
smtpClient.Send(message);
}
Thanks Sani. It was even stupider than that. My Site Host's web panel had two text boxes for changing the password, I I filled both out and hit save.
It also had a checkbox for "change Password" and I never noticed it.
So I had the wrong password. The code is fine. :)

Categories