Reading file line by line in listbox - c#

I tried to make my own email sender, but now I have issued to execute the mail list line by line. My current code is
foreach (string emails in listBoxEmails.Items)
{
mail.From.Add(new MailboxAddress(textBoxSendName.Text, textBoxSendFrom.Text));
mail.To.Add(new MailboxAddress(emails));
client.Send(mail);
Thread.Sleep(1000);
}
I want the the program run like, after I sent the 1st mail of the list was successful, it will send the second mail. but from my code that I got from google, it will directly sent all the email together.

You should write a method something like that returns true or false.
foreach (string email in listBoxEmails.Items)
{
if (!sendMail(textBoxSendName.Text, textBoxSendFrom.Text, email)){
break;
}
}
private bool sendMail(string name, string from, string to)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.????.???");
mail.From = new MailAddress(from, name, Encoding.UTF8);
mail.To.Add(to);
mail.Subject = "Test Mail";
mail.Body = "This is for testing...";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}

Related

C# How to set 'return-path' for smtp mail

I am trying to set the 'return-path' for my emails but I'm not seeing it as an available parameter. It seems like replytolist is not the same thing. I wan't to set the location that bounced emails are delivered. Here is my code so far:
private static void SendMail(string html,string taxId,string toEmail,string filePath,string fromEmail,string replyToEmail,string emailSubject,string emailAttachPath)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = emailSubject;
mail.Body = html;
//specify the priority of the mail message
mail.ReplyToList.Add(replyToEmail);
SmtpClient SmtpServer = new SmtpClient("smtp.server.com");
SmtpServer.Port = 25;
SmtpServer.UseDefaultCredentials = true;
SmtpServer.EnableSsl = false;
mail.IsBodyHtml = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
If you dont write return path emailaddress. Server will take from email address convert into the return path. You also can see email report in your email original source.
If you want to add custom reutn path you can use
MailMessage message = new MailMessage();
message.Headers.Add("Return-Path", "response#*****.biz");
Also if you using postfix and you want add return path Automatically You will have to make changes in two files
canonical :- put your return path emailaddress here.
//reply#domain.com
main.cf :- write your code in main.cf file
canonical_classes = envelope_sender
sender_canonical_maps = regexp:/etc/postfix/canonical

How can I ignore sending email method and continue execution?

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);

Loop for resending smtp email on failure to send

I have a service that sends an email after a user registers. Every once in a while, a user contacts support with the complaint that they aren't receiving the email, so I've made a list of possible issues, one of which is a smtp failure to send email, which I noticed occasionally when I would step through the code. I want to write a simple loop that tries to resend the email a couple of times on failure to send, but I'm not sure how to go about doing that. I'd appreciate any advice on the subject.
public void MusicDownloadEmail(string email)
{
try
{
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex)
{
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}
Something like this should do the trick:
public void MusicDownloadEmail(string email)
{
int tryAgain = 10;
bool failed = false;
do
{
try
{
failed = false;
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv
{
failed = true;
tryAgain--;
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}while(failed && tryAgain !=0)
}
You could do it recusively
Firstly define the maximum amount of retries
public const int MAX_RETRY_COUNT = 3;
Then call the method using the retry count
MusicDownloadEmail("code#mail.com", MAX_RETRY_COUNT);
And modify the method as follows
public static void MusicDownloadEmail(string email, int retryCountsLeft) {
if (retryCountsLeft > 1) {
try {
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
} catch (Exception ex) {
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
MusicDownloadEmail(email, --retryCountsLeft);
}
}
}

Smtp mail delivered unsuccessfully

I am using Smtp to send mail.A message was sent successfully but it was not delivered. What is the reason behind this.Is this a problem in mailing server?The message sending process is working fine for the last couple of years.The issue came first time.
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
Log.WriteSpecialLog("smtpClient mail sending first try success", "");
}
catch (Exception ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try Failed : " + ee.ToString(), "");
return false;
}
return true;
}
catch (Exception ex)
{
Log.WriteLog("smtpClient mail sending overall failed : " + ex.ToString());
return false;
}
}
A message was sent successfully but it was not delivered
If it was sent successfully from your mailing server then the possible reason of non delivery can be that the mail filter on client blocked it or is delivered in the junk.

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