C#发送SMTP邮件

主要要注意的是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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值