65.9K
CodeProject 正在变化。 阅读更多。
Home

从 C# 应用程序使用默认 SMTP 发送电子邮件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.60/5 (25投票s)

2004年9月14日

CPOL
viewsIcon

240646

downloadIcon

13049

使用System.Web.Mail通过默认SMTP从C#发送邮件

Screenshot - SendMail.jpg

引言

本文档提供了一个演示,展示了如何从C# Windows应用程序发送电子邮件。

描述

首先,在项目引用中添加引用(项目 -> 添加引用),然后选择 System.Web.dll 然后在你的类中包含 using System.Web.Mail ,并创建一个 MailMessage 对象,并将值赋给所有必需的属性。

MailMessage objMsg=new MailMessage();

if(ValidateEmail(txtTo.Text)==true) objMsg.To=txtTo.Text;

else throw new MyExp();

objMsg.From=sFrom;

if (txtCc.Text!="") objMsg.Bcc=txtBcc.Text;

if (txtBcc.Text!="") objMsg.Cc=txtCc.Text;

if (txtSubject.Text!="") objMsg.Subject=txtSubject.Text;

else throw new MyExp();

objMsg.Body=txtMessage.Text;

你也可以将附件与邮件一起发送。为此,我们可以使用 MailAttachment 对象,例如:

MailAttachment attach1;
string sFile;
if(lstfiles.Items.Count>0)
{
    for(int i=0;i<lstfiles.Items.Count;i++)
    {
        lstfiles.SelectedIndex=i;
        sFile=lstfiles.Text;
        attach1=new MailAttachment(sFile);
        objMsg.Attachments.Add(attach1);
    }
}

但在发送邮件之前,你必须通过点击“From”(发件人)按钮设置发件人字段和SMTP服务器。如果你在Windows 2000、Windows XP Professional、Windows Server 2003上使用,并且配置了smtp服务器,则可以将其留空。

然后,你可以通过点击“Send”(发送)按钮发送邮件。

SmtpMail.Send(objMsg); 

此外,当你运行此应用程序时,它将在系统托盘中显示,当你右键单击该图标时,它将显示弹出菜单。

mymenu=new ContextMenu();

mymenu.MenuItems.Add("Open",new System.EventHandler(open_Click));

mymenu.MenuItems.Add("Hide",new System.EventHandler(hide_Click));

mymenu.MenuItems.Add("Exit",new System.EventHandler(exit_Click));

myIcon=new NotifyIcon();

myIcon.Text="Right Click For Context Menu";

myIcon.Visible=true;

myIcon.Icon=new Icon(GetType(),"MAIL6.ICO");

myIcon.ContextMenu=mymenu;

以上图片显示了系统托盘中的弹出菜单,我们可以从中隐藏、打开和退出应用程序。

完整源代码

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Web.Mail;

using System.Text.RegularExpressions;

using MailOpt;

namespace MailTest

{

public class SendMail : System.Windows.Forms.Form

{

    private System.Windows.Forms.TextBox txtBcc;

    private System.Windows.Forms.Label label1;

    private System.Windows.Forms.Label label2;

    private System.Windows.Forms.Label label3;

    private System.Windows.Forms.Label label4;

    private System.Windows.Forms.Label label5;

    private System.Windows.Forms.Label label6;

    private System.Windows.Forms.Button button3;

    private System.Windows.Forms.Label label7;

    private System.Windows.Forms.OpenFileDialog dlgopenFile;

    private System.Windows.Forms.Button btnshowfile;

    private System.Windows.Forms.TextBox txtAttachment;

    private System.Windows.Forms.TextBox txtTo;

    private System.Windows.Forms.TextBox txtSubject;

    private System.Windows.Forms.TextBox txtCc;

    private System.Windows.Forms.RichTextBox txtMessage;

    private System.Windows.Forms.ListBox lstfiles;

    private System.Windows.Forms.Button btnSend;

    int c=0;

    public static string sFrom="";

    public static string sSmtpServer="";

    private System.Windows.Forms.Button btnFrom;

    NotifyIcon myIcon;

    ContextMenu mymenu;

    private System.ComponentModel.Container components = null;

    public SendMail()

    {

    InitializeComponent();

    }

    protected override void Dispose( bool disposing )

    {

        if( disposing )

        {

            if(disposing)

            {

                this.myIcon.Dispose();

            }

            if (components != null) 

            {

                components.Dispose();

            }

        }

            base.Dispose( disposing );


    }    

    [STAThread]

    static void Main() 

    {

        Application.Run(new SendMail());

    }

    private void btnSend_Click(object sender, System.EventArgs e)

    {

    try

    {

    if (sSmtpServer=="")

    {

    MessageBox.Show("You have not set any SmtpServer name! It will " & _
"use default Mail Server if you configured on your machine","SmtpServer Name Not Found",
MessageBoxButtons.OK,MessageBoxIcon.Information);

btnFrom.Focus();

}

else

{

SmtpMail.SmtpServer=sSmtpServer;

}

if(sFrom=="" || sFrom=="mailto:test@mail.com">test@mail.com)

{

MessageBox.Show("Please set your (Sender's) Address First","Sender Address",
MessageBoxButtons.OK,MessageBoxIcon.Error);

btnFrom.Focus();

return;

}


MailMessage objMsg=new MailMessage();

if(ValidateEmail(txtTo.Text)==true) objMsg.To=txtTo.Text;

else throw new MyExp();

objMsg.From=sFrom;

if (txtCc.Text!="") objMsg.Bcc=txtBcc.Text;

if (txtBcc.Text!="") objMsg.Cc=txtCc.Text;

if (txtSubject.Text!="") objMsg.Subject=txtSubject.Text;

else throw new MyExp();

objMsg.Body=txtMessage.Text;

MailAttachment attach1;//, attach2, attach3;


string sFile;

if(lstfiles.Items.Count>0)

{

for(int i=0;i<lstfiles.Items.Count;i++)

{

lstfiles.SelectedIndex=i;

sFile=lstfiles.Text;

attach1=new MailAttachment(sFile);

objMsg.Attachments.Add(attach1);

}

}

SmtpMail.Send(objMsg); 

lstfiles.Items.Clear();

MessageBox.Show("Mail Sent");

}

catch(Exception ex)

{

MessageBox.Show("Error :"+ex.ToString()); 

}

}

private void btnshowfile_Click(object sender, System.EventArgs e)

{

dlgopenFile.ShowDialog();

txtAttachment.Text=dlgopenFile.FileName;

lstfiles.Items.Add (txtAttachment.Text);

}

private void button3_Click(object sender, System.EventArgs e)

{

Environment.Exit(0);

}

private void SendMail_Load(object sender, System.EventArgs e)

{

mymenu=new ContextMenu();

mymenu.MenuItems.Add("Open",new System.EventHandler(open_Click));

mymenu.MenuItems.Add("Hide",new System.EventHandler(hide_Click));

mymenu.MenuItems.Add("Exit",new System.EventHandler(exit_Click));

myIcon=new NotifyIcon();

myIcon.Text="Right Click For Context Menu";

myIcon.Visible=true;

myIcon.Icon=new Icon(GetType(),"MAIL6.ICO");

myIcon.ContextMenu=mymenu;

}

protected void exit_Click(Object sender, System.EventArgs e) 

{

Close();

}

protected void hide_Click(Object sender, System.EventArgs e) 

{

Hide();

}

protected void open_Click(Object sender, System.EventArgs e) 

{

Show();

}


public bool ValidateEmail(string sEmail)

{

Regex exp=new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

Match m=exp.Match(sEmail);

if(m.Success && m.Value.Equals(sEmail)) return true;

else return false;

}


private void btnFrom_Click(object sender, System.EventArgs e)

{

MailOpt.frmFrom frm=new MailOpt.frmFrom();

frm.Show();

}

}

class MyExp: Exception

{

public override string ToString()

{

return " Value is Blank or Invalid";

}

}

}


//Other frmForm.cs



using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using MailTest;

namespace MailOpt

{

public class frmFrom : System.Windows.Forms.Form

{

private System.Windows.Forms.TextBox txtFrom;

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Button btnok;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.TextBox txtSmtpServer;

private System.Windows.Forms.Label label2;

private System.ComponentModel.Container components = null;

public frmFrom()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if(components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}


#region Windows Form Designer generated code

#endregion

private void btnok_Click(object sender, System.EventArgs e)

{

SendMail.sFrom=txtFrom.Text;

SendMail.sSmtpServer=txtSmtpServer.Text;

Dispose();

}

private void button1_Click(object sender, System.EventArgs e)

{

Dispose();

}

}

}

© . All rights reserved.