在MVC中发送Email 可以使用WebMail ;使用起来十分简单。如下:
WebMail.SmtpServer = ConfigurationHelper.GetValue("SmtpServer");//获取或设置要用于发送电子邮件的 SMTP 中继邮件服务器的名称。 WebMail.SmtpPort = Int32.Parse(ConfigurationHelper.GetValue("SmtpPort"));//发送端口 WebMail.EnableSsl = true;//是否启用 SSL GMAIL 需要 而其他都不需要 具体看你在邮箱中的配置 WebMail.UserName = ConfigurationHelper.GetValue("UserName");//账号名 WebMail.From = ConfigurationHelper.GetValue("From"); //邮箱名 WebMail.Password = ConfigurationHelper.GetValue("Password");//密码 WebMail.SmtpUseDefaultCredentials = true;//是否使用默认配置 WebMail.Send(to: email, subject: "注册验证信息", body: Utility.String.EmailHtml(email));
当然这里我将常用的配置信息都写在了web.config 中使用 ConfigurationHelper(自己封装的) 读取相关配置信息
这里使用AES加密和解密实现了不用往数据库里面存邮箱的注册功能。
我获取到了一个邮箱先AES加密 将得到的字符串发给用户。用户点击链接穿过来加密的字符串,我们行进解密。得到一个邮箱则继续注册。
当然 ASE首先向自己设置一个向量 和密钥。
/// <summary> /// AES加密 /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>密文</returns> public static string AESEncrypt(string Data) { Byte[] plainBytes = Encoding.UTF8.GetBytes(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] Cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流 using (MemoryStream Memory = new MemoryStream()) { // 把内存流对象包装成加密流对象 using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { // 明文数据写入加密流 Encryptor.Write(plainBytes, 0, plainBytes.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } } } catch { Cryptograph = null; } return Convert.ToBase64String(Cryptograph); } /// <summary> /// AES解密 /// </summary> /// <param name="Data">被解密的密文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>明文</returns> public static string AESDecrypt(string Data) { Byte[] encryptedBytes = Convert.FromBase64String(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] original = null; // 解密后的明文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流,存储密文 using (MemoryStream Memory = new MemoryStream(encryptedBytes)) { // 把内存流对象包装成加密流对象 using (CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read)) { // 明文存储区 using (MemoryStream originalMemory = new MemoryStream()) { Byte[] Buffer = new Byte[1024]; Int32 readBytes = 0; while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } original = originalMemory.ToArray(); } } } } catch { original = null; } return Encoding.UTF8.GetString(original); }