How can I ignore sending email method and continue execution? - c#

I'm sending email using C#. It's working fine when internet is available, but it is returning exception message again and again and stop execution when internet connection is not available. How do I ignore sending email and continue execution if connection is not available,
or any other suitable method to do that..
while (true)
{
try
{
Thread.Sleep(50);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail");
mail.To.Add("mymail");
mail.Subject = "data - 1";
mail.Body = "find attachement";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filepath);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception)
{
MessageBox.Show("Internet Connection is not found");
}
}

Any solution which depends on repeated attempts may end up looping endlessly.
Your code is sending the email synchronously, why not send asynchronously using the pickup directory
This will drop the email into the SMTP pickup directory, and the SMTP server will handle transient network issues, by retrying for a configurable period of time.

Just break out of the loop when there's no internet :
while (true)
{
try
{
Thread.Sleep(50);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail");
mail.To.Add("mymail");
mail.Subject = "data - 1";
mail.Body = "find attachement";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filepath);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception)
{
MessageBox.Show("Internet Connection is not found");
break;
}
}

It will be better to have a testconnection method and if it returns true to send the email. Something like:
while(true)
{
if(TestConnection())
{
SendEmail(); // you should leave the try...catch.. anyway in case
// the connection failed between the TestConnection
// and the SendEmail() operation. But then do not
// prompt a messagebox, just swallow
Thread.Sleep(50);
}
}
Now the TestConnection implementation, you can try to get help from the following link:
enter link description here

Try this:
while (true)
{
try
{
Thread.Sleep(50);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail");
mail.To.Add("mymail");
mail.Subject = "data - 1";
mail.Body = "find attachement";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filepath);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.InnerException);
return false;
}
}
Or you can set a bool to true and then check in the end if the bool is true of false
FX:
string noInterNet = "";
while (true)
{
try
{
Thread.Sleep(50);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail");
mail.To.Add("mymail");
mail.Subject = "data - 1";
mail.Body = "find attachement";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filepath);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
noInterNet = ex.InnerException;
}
}
And then in the end of the code do:
if(noInterNet != "")
MessageBox.Show("Error " + noInterNet);

Related

Sending Email in C# without authenticating

I've tried this code to send Email without entering credentials :
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp server");
mail.From = new MailAddress("sender email");
mail.To.Add("receiver email");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = CredentialCache.DefaultNetworkCredentials;
SmtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I get this server error:
Sytem.Net.Mail.SmtpException 5.7.3 Requested action aborted;user not
authentificated
I've also tried:
SmtpServer.UseDefaultCredentials = false;
Still the same exception is thrown.

Email configuration

Hi guys I am doing email function for the first time and I searched up on how to do a email
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("from#gmail.com");
message.To.Add(new MailAddress("to#gmail.com"));
message.Subject = "Test";
message.Body = "Content";
smtp.Port = 587;
smtp.Host = "gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential("from#gmail.com", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex.Message);
}
I tried running this but I am not sure what is the problem... i did not use IIS or anything
(update)
I uploaded the error image in this website
http://imgur.com/3vVZhsW
This one will Help you..! try this..!
try
{
MailMessage Msg = new MailMessage();
// Sender e-mail address.
SmtpClient smtp = new SmtpClient();
//smtp object.
Msg.From = new MailAddress("from#gmail.com");
// Recipient e-mail address.
Msg.To.Add(to#gmail.com);
//here you can pass textbox value how need to send mail.
Msg.Subject = "Please confirm your subscription";
Msg.Body = "<body></body>";
Msg.IsBodyHtml = true;
// your remote SMTP server IP.
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("from#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(Msg);
//Msg = null;
}
catch(Exception ex)
{
Message.Show("Error:" + ex.Message);
}

mail was not sending

void sendMail(string invoiceNumber)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("Smtp.gmail.com");
mail.From = new MailAddress("*******#gmail.com");
mail.To.Add("******#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = invoiceNumber;
mail.Subject = "PDFs Attached";
DirectoryInfo di = new DirectoryInfo(#"C:\Users\User\Desktop\test\");
foreach (var file in di.GetFileSystemInfos("*.pdf*"))
mail.Attachments.Add(new Attachment(file.FullName));
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("*******#gmail.com", "*********");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
https://www.google.com/settings/security/lesssecureapps use this link to Allow less secure apps on of your gmail id....
void sendMail(string invoiceNumber)
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add("recevermailid");
mail.From = new MailAddress("sender id");
mail.Subject = "Confirmation";
string Body = "your message body";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("sender email", "seneder email password");// Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

C# Windows Form Application - Send email using gmail smtp

I have been trying to create a small program to send email through smtp.gmail.com, but it always prompt me that "The operation has timed out".
I know there are lots of solutions available on the net but none of it works.
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("from#gmail.com");
message.To.Add(new MailAddress("to#gmail.com"));
message.Subject = "Test";
message.Body = "Content";
smtp.Port = 465;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("from#gmail.com", "pwd");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex.Message);
}
Is there any way to solve this?
Change the port to 587:
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("from#gmail.com");
message.To.Add(new MailAddress("to#gmail.com"));
message.Subject = "Test";
message.Body = "Content";
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("from#gmail.com", "pwd");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("err: " + ex.Message);
}
how to how to send email of pdf file which is store in d drive in c# windows
application...the answer is...
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtFrom.Text.ToString());
mail.To.Add(txtmailTo.Text.ToString());
mail.Subject = "Mail Pdf";
var filename = #"D:/your file path/.pdf";
mail.Attachments.Add(new Attachment(filename));
SmtpServer.Port = 587;
SmtpServer.Credentials = new
System.Net.NetworkCredential(txtFrom.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
you can use SMTP protocol to send this image as an Attachment, your code will be something like that :
using MailKit.Net.Smtp; using MimeKit;
MimeMessage message = new MimeMessage();
BodyBuilder Attachmint = new BodyBuilder();
message.From.Add(new MailboxAddress("name sender", "Mail From"));
message.To.Add(MailboxAddress.Parse("Mail To"));
message.Subject = Subject;
message.Body = new TextPart("plain")
{
Text = tex_body.Text + Massage
};
Attachmint.Attachments.Add("Attatchment Path");
message.Body = Attachmint.ToMessageBody();
SmtpClient client = new SmtpClient();
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("Mail from", "Password mail");
client.Send(message);

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}

Categories

Resources