try { from = "\"Lithotech Account in C# Application\" <" + txtFrom.Text + ">"; to = txtTo.Text; user = txtTo.Text; subject = txtSubject.Text; message = txtMessage.Text; SmtpClient client = new SmtpClient("155.236.11.143", 25); client.Credentials = new NetworkCredential(username, password); client.EnableSsl = false; StringBuilder mailBody = new StringBuilder("."); int n = user.IndexOf("@"); if (n != -1) { mailBody.AppendLine("<h1>Dear " + user.Substring(0, n) + "</h1>"); } mailBody.AppendLine("<br />"); mailBody.AppendLine("<p>" + message + "</p>"); MailMessage msg = new MailMessage(from, to, subject, mailBody.ToString()); msg.IsBodyHtml = true; DialogResult attachment = MessageBox.Show("Do you want to add any attachments?", "Attachments", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (attachment == DialogResult.Yes) { Cursor.Current = Cursors.WaitCursor; OpenFileDialog file = new OpenFileDialog(); file.Filter = "Text Files (*.txt)|*.txt|C Sharp Files (*.cs)|*.cs"; file.Title = "Add attachments";
if (file.ShowDialog() == DialogResult.Cancel) return; FileStream fstream; try { fstream = new FileStream(file.FileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fstream); while (reader.Peek() >= 0) { string str = reader.ReadLine(); richTextBox1.Text += str + '\n'; } Attachment attatchment = new Attachment(file.FileName); msg.Attachments.Add(attatchment); string AttFileName = new System.IO.FileInfo(@file.FileName).Name; MessageBox.Show(AttFileName + " as Attachment added", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); Cursor.Current = Cursors.WaitCursor; client.Send(msg); Cursor.Current = Cursors.WaitCursor; MessageBox.Show("Message and attachment sent successfully!", "Sent Message", MessageBoxButtons.OK, MessageBoxIcon.Information); Cursor.Current = Cursors.Default; txtTo.Clear(); txtSubject.Clear(); txtMessage.Clear(); txtTo.Focus(); } catch (Exception) { MessageBox.Show("Error opening file", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else if (attachment == DialogResult.No) { Cursor.Current = Cursors.WaitCursor; client.Send(msg); MessageBox.Show("Message sent successfully!", "Sent Message", MessageBoxButtons.OK, MessageBoxIcon.Information); Cursor.Current = Cursors.Default; txtTo.Clear(); txtSubject.Clear(); txtMessage.Clear(); txtTo.Focus(); } } catch (Exception ex) { MessageBox.Show("Unable to send message due to the following reason: " + '\n' + ex.Message); } }
|