您的位置:首页 > 编程语言 > C#

C#发送SMTP邮件

2012-03-09 00:00 309 查看
主要要注意的是smtp认证的问题。代码很简单,如下:

调用代码:

namespace EmailTest

{

class Program

{

static void Main(string[] args)

{

try

{

SMTPEmailSender sender = new SMTPEmailSender("mail.longdayinfo.com", "upcodechina@longdayinfo.com", "12345");

sender.From = "upcodechina@longdayinfo.com";

sender.AddReceiver("csfreebird@gmail.com");

sender.Subject = "This is a test";

sender.Content = "hi,beijing team";

sender.AddAttachment("C://aa.jpg");

sender.AddAttachment("C://aaa.csv");

sender.Send();

System.Console.Out.WriteLine("send ok");

}

catch(Exception e)

{

System.Console.Out.WriteLine(e.Source+e.Message);

}

}

}

}

SMTPEmailSender类的源代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net.Mail;

using System.Net;

namespace Freebird

{

public class SMTPEmailSender

{

//If your smtp server wants authentication,use it

public SMTPEmailSender(String smtpServer,String user,String password)

{

mailMessage = new MailMessage();

smtpClient = new SmtpClient();

smtpClient.Host = smtpServer;

smtpClient.Port = 25;

smtpClient.Credentials = new NetworkCredential(user, password);

}

//If your smtp server doesn't want authentication,use it

public SMTPEmailSender(String smtpServer)

{

mailMessage = new MailMessage();

smtpClient = new SmtpClient(smtpServer);

}

public String Subject

{

get

{

return mailMessage.Subject;

}

set

{

mailMessage.Subject = value;

}

}

//get/set the email's content

public String Content

{

get

{

return mailMessage.Body;

}

set

{

mailMessage.Body = value;

}

}

public String From

{

get

{

return mailMessage.From.Address;

}

set

{

mailMessage.From = new MailAddress(value);

}

}

public void AddReceiver(String email)

{

mailMessage.To.Add(email);

}

public void Send()

{

smtpClient.Send(mailMessage);

}

public void AddAttachment(String filename)

{

mailMessage.Attachments.Add(new Attachment(filename));

}

private MailMessage mailMessage;

private SmtpClient smtpClient;

}

}

$(document).ready(function(){dp.SyntaxHighlighter.HighlightAll('code');});

原文链接:
http://blog.csdn.net/sheismylife/article/details/2078131
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: