发送电子邮件失败但有例外

时间:2014-01-03 22:33:20

标签: c# .net email

我尝试使用类(其源代码,我没有)和C#脚本(结尾)发送邮件。

我可以使用该类发送邮件,但不能使用C#脚本发送邮件。我收到了错误 -

System.Reflection.TargetInvocationException: Exception has been thrown 
by the target of an invocation. 
---> System.Net.Mail.SmtpException: Failure sending mail. 
---> System.Net.WebException: Unable to connect to the remote server 
---> System.Net.Sockets.SocketException: No connection could be made 
because the target machine actively refused it YourIPAddress

我知道这个类在C#代码中使用完全相同的信息。所以,我是 猜测这是因为某些默认/ Windows凭据或其他东西 那样的,但我不确定。我如何弄清楚为什么会这样,以及如何发生 我能解决它吗?

代码 -

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Net.Mail;        

    public void Main()
    {
        String SendMailFrom = "abc@aol.com";
        String SendMailTo = "james@apple.com";
        String SendMailSubject = "Hello !";
        String SendMailBody = "Hello Email!";

        String SmtpServer = "smtp.apple.com";

        MailMessage myHtmlFormattedMail = new MailMessage(SendMailFrom, 
        SendMailTo, SendMailSubject, SendMailBody);
        myHtmlFormattedMail.IsBodyHtml = true;

        SmtpClient mySmtpClient = new SmtpClient(SmtpServer);
        mySmtpClient.Port = 2525; 
        mySmtpClient.Send(myHtmlFormattedMail);

      }

    }

}

2 个答案:

答案 0 :(得分:1)

using System;
using System.Net;
using System.Net.Mail;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            SendMail("smtp.gmail.com", "mymail@gmail.com", "myPassword", "yourmail@gmail.com", "e-mail subject", "body of the email", "data.xls");
        }

        public static void SendMail(string smtpServer, string from, string password, string mailto, 
            string caption, string message, string attachFile = null)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from);
                mail.To.Add(new MailAddress(mailto));
                mail.Subject = caption;
                mail.Body = message;

                if (!string.IsNullOrEmpty(attachFile))
                    mail.Attachments.Add(new Attachment(attachFile));
                SmtpClient client = new SmtpClient();
                client.Host = smtpServer;
                client.Port = 587;
                client.EnableSsl = true;
                client.Credentials = new NetworkCredential(from.Split('@')[0], password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Send(mail);
                mail.Dispose();
            }
            catch (Exception e)
            {
                throw new Exception("Mail.Send: " + e.Message);
            }
        }
    }
}

答案 1 :(得分:0)

您似乎没有传递任何凭据,Apple也不允许未经授权发送电子邮件。

尝试:

SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");

另外,你确定有一台运行@ smtp.apple.com:2525的SMTP服务器吗?