private void button2_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "(*.xml)|*.xml"; sfd.FilterIndex = 1; if (sfd.ShowDialog() == DialogResult.OK) { List <string> lfile = null; if (listView1.Items.Count > 0) { lfile = new List <string>(); for (int i = 0; i < listView1.Items.Count; i++) { lfile.Add(listView1.Items[i].Text); } } SaveMailParam smp = new SaveMailParam(textBox3.Text, Int32.Parse(textBox7.Text), textBox4.Text, textBox5.Text, checkBox1.Checked, textBox1.Text, textBox6.Text, checkBox2.Checked, textBox2.Text, lfile, textBox8.Text); Serial(sfd.FileName, smp); } }
private void button6_Click(object sender, EventArgs e) { OpenFileDialog Open = new OpenFileDialog(); Open.Filter = "(*.xml)|*.xml"; Open.FilterIndex = 1; if (Open.ShowDialog() == DialogResult.OK) { SaveMailParam smp = DeSerial(Open.FileName); if (smp != null) { textBox3.Text = smp.SMTPServer; textBox7.Text = smp.SMTPPort.ToString(); textBox4.Text = smp.FromMail; textBox5.Text = smp.FromPassword; checkBox1.Checked = smp.SSL; textBox8.Text = smp.DisplayName; textBox1.Text = smp.ToMail; textBox6.Text = smp.Tema; textBox2.Text = smp.Text.Replace("\n", Environment.NewLine); checkBox2.Checked = smp.isHTML; listView1.Items.Clear(); if ((smp.FileNames != null) && (smp.FileNames.Count > 0)) { for (int i = 0; i < smp.FileNames.Count; i++) { FileInfo fileInf = new FileInfo(smp.FileNames[i]); if (fileInf.Exists) { long l = fileInf.Length; ListViewItem lll = listView1.Items.Add(smp.FileNames[i]); lll.SubItems.Add(l.ToString()); lll.Tag = l; } } long summ = 0; for (int i = 0; i < listView1.Items.Count; i++) { summ = summ + (long)listView1.Items[i].Tag; } label8.Text = summ.ToString(); } } } }
private void button1_Click(object sender, EventArgs e) { List <string> lfile = null; if (listView1.Items.Count > 0) { lfile = new List <string>(); for (int i = 0; i < listView1.Items.Count; i++) { lfile.Add(listView1.Items[i].Text); } } SaveMailParam smp = new SaveMailParam(textBox3.Text, Int32.Parse(textBox7.Text), textBox4.Text, textBox5.Text, checkBox1.Checked, textBox1.Text, textBox6.Text, checkBox2.Checked, textBox2.Text, lfile, textBox8.Text); SendMail(smp, null); }
bool Serial(string fname, SaveMailParam smp) { bool ret = false; try { XmlSerializer formatter = new XmlSerializer(typeof(SaveMailParam)); using (FileStream fs = new FileStream(fname, FileMode.OpenOrCreate)) { formatter.Serialize(fs, smp); } ret = true; } catch (Exception e) { MessageBox.Show(fname + " - " + e.Message); } return(ret); }
static public SaveMailParam DeSerial(string fname, bool MessageBoxShow = true) { SaveMailParam smp = null; try { XmlSerializer formatter = new XmlSerializer(typeof(SaveMailParam)); using (FileStream fs = new FileStream(fname, FileMode.OpenOrCreate)) { smp = (SaveMailParam)formatter.Deserialize(fs); } } catch (Exception e) { if (MessageBoxShow) { MessageBox.Show(fname + " - " + e.Message); } } return(smp); }
static public void SendMail(SaveMailParam smp, StateMail userState) //Передать параметром чтобы не вызывал сообщения { MailMessage mess = null; SmtpClient client = null; try { client = new SmtpClient(smp.SMTPServer, smp.SMTPPort); client.Credentials = new NetworkCredential(smp.FromMail.Split('@')[0], smp.FromPassword); //Выключаем или включаем SSL - (например для гугла и mail должен быть включен). client.EnableSsl = smp.SSL; client.DeliveryMethod = SmtpDeliveryMethod.Network; mess = new MailMessage(); mess.From = new MailAddress(smp.FromMail, smp.DisplayName); //отображаемое имя string[] masTo = smp.ToMail.Split(';'); if (masTo.Length > 0) { for (int i = 0; i < masTo.Length; i++) { mess.To.Add(new MailAddress(masTo[i].Trim())); } } mess.Subject = smp.Tema; mess.Body = smp.Text; mess.IsBodyHtml = smp.isHTML; client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); } catch (Exception e) { if (userState != null) { if (userState.MessageBoxShow) { MessageBox.Show(e.Message); } userState.EvenWaitH.Set(); } else { MessageBox.Show(e.Message); } return; } if ((smp.FileNames != null) && (smp.FileNames.Count > 0)) { for (int i = 0; i < smp.FileNames.Count; i++) { //Теперь прикрепим файл к сообщению... try { string file = smp.FileNames[i]; // Тип файла не определен Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet); // Добавляем информацию для файла ContentDisposition disposition = attach.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); mess.Attachments.Add(attach); } catch (Exception e) { if (userState != null) { if (userState.MessageBoxShow) { MessageBox.Show(smp.FileNames[i] + " - " + e.Message); } userState.EvenWaitH.Set(); } else { MessageBox.Show(smp.FileNames[i] + " - " + e.Message); } return; } } } client.SendAsync(mess, userState); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); string[] mascommand = Environment.CommandLine.Split('/'); if (mascommand.Length > 2) { bool MessageBoxShow = false; try { MessageBoxShow = Int32.Parse(mascommand[1].Trim()) == 1; } catch { } // Первый параметр обязательный 1 или 0 Включить или нет сообщение о об статусе завершения отправки почты // Второй параметр обязательный Имя файла ***.xml с конфигурацией создоваемой если запустить программу без параметров SaveMailParam smp = Form1.DeSerial(mascommand[2].Trim(), MessageBoxShow); if (smp != null) { smp.Text = smp.Text.Replace("\n", Environment.NewLine); for (int i = 3; i < mascommand.Length; i++) { int pos = mascommand[i].IndexOf(':'); if (pos > -1) { string se = mascommand[i].Remove(0, pos + 1); se = se.Trim(); string ss = mascommand[i].Substring(0, pos); //MessageBox.Show("-"+ss + "- -"+se+"-"); switch (ss.Trim().ToUpper()) { case "SM": smp.SMTPServer = se; break; // - SMTP сервер case "PT": try { smp.SMTPPort = Int32.Parse(se); } catch { } break; // - Порт case "FR": smp.FromMail = se; break; // - Адрес отправителя case "PS": smp.FromPassword = se; break; // - Пароль case "SL": try { smp.SSL = Int32.Parse(se) == 1; } catch { } break; // - SSL case "DN": smp.DisplayName = se; break; // Имя адреса case "ML": if (se.Length > 0) { if (smp.ToMail.Length > 0) { smp.ToMail = smp.ToMail + ";" + se; } else { smp.ToMail = se; } } break; // Добавление - Адреса получателя case "MLC": smp.ToMail = se; break; // С очисткой- Адрес получателя case "TP": smp.Tema = se; break; // - Заголовок отправления case "TX": smp.Text = smp.Text + se; // Добавляется текст к последней строке break; // - Текст письма case "TXT": smp.Text = se + Environment.NewLine + smp.Text; // Добавляется текст перед уже существующим break; // - Текст письма case "TXN": smp.Text = smp.Text + se + Environment.NewLine; // Добавляется текст к последней строке с переводом на следущую строку break; // - Текст письма case "TXC": smp.Text = se; break; // С удалением предидущего текста - Текст письма case "TXF": // Загрузка текста из файла try { smp.Text = File.ReadAllText(se, Encoding.GetEncoding(1251)); //"windows-1251"));//"koi8-r")); } catch (Exception e) { if (MessageBoxShow) { MessageBox.Show(se + " - " + e.Message); } } break; case "FL": if (se.Length > 0) { if (smp.FileNames == null) { smp.FileNames = new List <string>(); } smp.FileNames.Add(se); } break; // - Файл прикрепленный case "FLC": if (smp.FileNames != null) //Очистка списка файлов { smp.FileNames.Clear(); } if (se.Length > 0) { if (smp.FileNames == null) { smp.FileNames = new List <string>(); } smp.FileNames.Add(se); } break; case "HT": try { smp.isHTML = Int32.Parse(se) == 1; } catch { } break; // - isHTML default: break; } } } EventWaitHandle EvenWaitH = new AutoResetEvent(false); StateMail sm = new StateMail(EvenWaitH, MessageBoxShow); Form1.SendMail(smp, sm); EvenWaitH.WaitOne(); Thread.Sleep(100); if (sm.Result) { Environment.Exit(0); } else { Environment.Exit(11000); } } else { Environment.Exit(11000); } } Application.Run(new Form1()); }