基本信息
源码名称:email sender邮件发送
源码大小:0.03M
文件格式:.zip
开发语言:C#
更新时间:2017-04-18
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 1 元 
   源码介绍

外国人写的email 发送程序

Usually, when we send an email, we need to login to a known email service provider's SMTP server and deliver the email
using that server. If we add the send email functionality to a software, the user needs to configure an SMTP server address,
the username, and the password. Why not send an email to the receiver's SMTP server directly? Because the receiver's server
doesn't need authorization, otherwise you can only receive email when the sender knows your account password. I think
many programmers have been asking this question, so I explored the issue.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace QiHe.CodeLib.Net
{
public class EmailSender
{
/// <summary>
/// Default SMTP Port.
/// </summary>
public static int SmtpPort = 25;
public static bool Send(string from, string to, string subject, string body)
{
string domainName = GetDomainName(to);
IPAddress[] servers = GetMailExchangeServer(domainName);
foreach (IPAddress server in servers)
{
try
{
SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
client.Send(from, to, subject, body);
return true;
}
catch
{
continue;
}
}
return false;
}
public static bool Send(MailMessage mailMessage)
{
string domainName = GetDomainName(mailMessage.To[0].Address);
IPAddress[] servers = GetMailExchangeServer(domainName);
foreach (IPAddress server in servers)
{
try
{
SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
client.Send(mailMessage);
return true;
}
catch
{
continue;
}
}
return false;
}
public static string GetDomainName(string emailAddress)
{
int atIndex = emailAddress.IndexOf('@');
if (atIndex == -1)
{
throw new ArgumentException("Not a valid email address",
"emailAddress");
}
if (emailAddress.IndexOf('<') > -1 &&
emailAddress.IndexOf('>') > -1)
{
return emailAddress.Substring(atIndex 1,
emailAddress.IndexOf('>') - atIndex);
 
}
else
{
return emailAddress.Substring(atIndex 1);
}
}
public static IPAddress[] GetMailExchangeServer(string domainName)
{
IPHostEntry hostEntry =
DomainNameUtil.GetIPHostEntryForMailExchange(domainName);
if (hostEntry.AddressList.Length > 0)
{
return hostEntry.AddressList;
}
else if (hostEntry.Aliases.Length > 0)
{
return System.Net.Dns.GetHostAddresses(hostEntry.Aliases[0]);
}
else
{
return null;
}
}
}
}