测试服务器SMTP是否可用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SeverEmailTest
{
public partial class Main_Frm : Form
{
System.Net.Mail.MailMessage TheMail;
public Main_Frm()
{
InitializeComponent();
}
private void bt_Send_Click(object sender, EventArgs e)
{
TheMail = new System.Net.Mail.MailMessage();
TheMail.From = new System.Net.Mail.MailAddress("Jack@XXXX.com", "Jack China");
string[] _addresses = txt_AddressTo.Text.Split(';');
foreach (string _item in _addresses)
{
if (string.IsNullOrEmpty(_item) == false)
{
if (isEmailAddress(_item) == false)
{
MessageBox.Show( "the email address : " + _item + " is invalid");
return;
}
TheMail.To.Add(_item);
}
}
if (TheMail.To.Count == 0)
{
TheMail.To.Add("jacks@XXXX.com");
}
string SMTPServer = this.txt_SMTP.Text.Trim();
if (string.IsNullOrEmpty(SMTPServer))
{
SMTPServer = "LocalHost";
}
TheMail.Subject = string.Format("This is a test email from {0},the smptp {1} is ok", Environment.MachineName, SMTPServer);
TheMail.Body = txt_Content.Text ;
TheMail.IsBodyHtml = false;
TheMail.BodyEncoding = Encoding.UTF8;
TheMail.Priority = System.Net.Mail.MailPriority.Normal;
string _result = "";
try
{
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (SMTPServer != "")
{
smtpClient.Host = SMTPServer;
}
string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["SmtpUserName"];
string SmtpPassword = System.Configuration.ConfigurationManager.AppSettings["SmtpPassword"];
if (string.IsNullOrEmpty(smtpUserName) == false && string.IsNullOrEmpty(SmtpPassword) == false)
{
smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, SmtpPassword);
}
smtpClient.Send(TheMail);
_result = "Successfully";
}
catch (Exception ex)
{
_result = ex.Message + "--" + ex.InnerException + "--" + ex.StackTrace;
}
MessageBox.Show(_result);
}
public bool isEmailAddress(string address)
{
//string expr = @"^[a-z0-9A-Z_\-\.]+[@]{1}[a-z0-9A-Z_\-\.]+[\.]{1}[a-z0-9A-Z_\-\.]+$";
string expr = @"((^[a-zA-Z0-9]+[a-z0-9A-Z_\-\.]*[a-z0-9A-Z_\-]+)|(^[a-zA-Z0-9]+))[@]{1}[a-zA-Z0-9]+[a-z0-9A-Z_\-\.]*[\.]{1}[a-z0-9A-Z_\-\.]*[a-zA-Z0-9]+$";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(expr);
bool eval = reg.IsMatch(address);
if (eval)
{
expr = @"\.{2,}";
reg = new System.Text.RegularExpressions.Regex(expr);
eval = !reg.IsMatch(address);
}
return eval;
}
private void bt_Cancel_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
}
}
}
浙公网安备 33010602011771号