我想从.NET中的服务器向我的邮件发送一封虚拟邮件。
我只是在没有操纵的情况下发送邮件:请让我知道我哪里出错了。我编写了如下代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendingEmail.aspx.cs" Inherits="experiments_asp_SendingEmail" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h2>Send e-mail to someone@example.com:</h2>
<asp:Button Text="Submit" OnClick="sendMail" runat="server"/>
</form>
</body>
</html>
我的.Net代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class experiments_asp_SendingEmail : System.Web.UI.Page
{
protected void sendMail(object sender, EventArgs e)
{
Console.Write("came here");
CreateTestMessage2("my college server"); //
}
public static void CreateTestMessage2(string server)
{
string to = "xyz@gmail.com";
string from = "xyz@gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
client.UseDefaultCredentials = true;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
}
如果此代码中有任何问题,请告诉我,我是否需要添加任何额外的内容。
点击提交后,我没有收到任何错误。
期望:发送虚拟邮件。请注意我是&lt;
的新手答案 0 :(得分:2)
我认为您需要向SMTP服务器提供更多信息才能接受您的请求。让我们以Gmail为例。我已经使用了您的代码并使其能够从google smtp服务器分发电子邮件:
string to = "xyz@gmail.com";
string from = "xyz@gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = true;
NetworkCredential nc = new NetworkCredential("yourEmail@gmail.com", "yourPassword");
client.Credentials = nc;
try
{
client.Send(message);
MessageBox.Show("Your message was sent.");
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
如您所见,您需要指定smtp服务器正在侦听的活动端口,并允许SSL消息传输。另一个关键部分是提供可接受的凭据,SMTP服务器可以验证用户进行身份验证。也许你的大学服务器有类似的架构。你管理服务器还是其他人?