使用EnableSSL发送电子邮件= true抛出AuthenticationException

时间:2014-09-19 10:03:07

标签: email

我使用以下代码发送带有EnableSsl = true的电子邮件,抛出以下异常:

System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

public static void SendEmailBySmtpServer(int currentSendCount)
        {
            try
            {
                var emailBodyJson = "Period Send Email From Service at -" + DateTime.Now +" Times="+currentSendCount;
                emailBodyJson += " EnableSsl=" + ConfigurationManager.AppSettings["SmtpServer.EnableSsl"];
                NameValueCollection appSettings = ConfigurationManager.AppSettings;
                string fromEmailAddress = appSettings["SmtpServer.FromEmailAddress"];
                string toEmailAddress = appSettings["SmtpServer.UserFeedback.ToEmailAddress"];
                string host = appSettings["SmtpServer.Host"];

                var smtpClient = new SmtpClient(host);
                var message = new MailMessage();

                message.From = new MailAddress(fromEmailAddress);
                message.To.Add(new MailAddress(toEmailAddress));
                message.Subject = emailBodyJson;
                message.IsBodyHtml = true;
                message.Body = emailBodyJson;

                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.EnableSsl = Convert.ToBoolean(appSettings["SmtpServer.EnableSsl"]);//if this changed to true then send failed
                smtpClient.UseDefaultCredentials = true;

                smtpClient.Send(message);

                logger.Info("Send Email Count = "+currentSendCount);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

1 个答案:

答案 0 :(得分:0)

要发送电子邮件,您可以使用以下代码,它的工作原理,但您必须使用相应的.jar文件。

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

 public class Email {

private static String USER_NAME = "xxxx";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "xxxxx"; // GMail password

private static String RECIPIENT = "xxxxx@xxxx.com";

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; // list of recipient email addresses
    String subject = "Java send mail example";
    String body = "hi ..this is a test mail,!";

    sendFromGMail(from, pass, to, subject, body);
 }

  private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
  String host = "smtp.gmail.com";
   // String host="localhost";
  // props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.starttls.enable", "true");
   // props.put("mail.smtp.host", host);
    props.put("mail.smtp.ssl.trust", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");//587
    props.put("mail.smtp.auth", "true");
    //System.out.println("success point 1");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
       //  System.out.println("success point 2");

        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

         //System.out.println("success point 3");

        message.setSubject(subject);
        message.setText(body);
        // System.out.println("success point 4");

        Transport transport = session.getTransport("smtp");
        // System.out.println("success point 5");

        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
       // System.out.println("success 6");
     }
     catch (AddressException ae) {
        ae.printStackTrace();
     }
     catch (MessagingException me) {
        me.printStackTrace();
     }
   }
}