2012-04-04 7 views
4

Хорошо, я не знаю, что еще делать. Этот код работал отлично, неделю назад, когда я написал и протестировал его. Затем я включил его в свою программу и понял, что получаю исключения. Все кажется нормальным. Адрес отправителя является законным. Адреса получателей, которые я использовал для проверки, является законным. Что не так? Я так расстроен:JavaMail - адрес отправителя отклонен: доступ запрещен

private String outgoingMailServer = "smtp.mail.yahoo.com"; 

boolean debug = true; 

      //set the host outgoing mail smtp server. 
      Properties properties = new Properties(); 
      properties.put("mail.smtp.host", outgoingMailServer); 
      properties.put("mail.smtp.auth", "true"); 

      Authenticator authenticator = new SMTPAuthentication(); 
      Session session = Session.getDefaultInstance(properties, authenticator); 

      session.setDebug(debug); 

      //create a message session 
      Message msg = new MimeMessage(session); 

      //set the addresses, to and from 
      InternetAddress fromAddress; 
      fromAddress = new InternetAddress(emailFromAddress); 
      msg.setFrom(fromAddress); 

      //since mail can be sent to more than one recipient, create loop 
      //to add all addresses into InternetAddress, addressTo. 
      //InternetAddress[] toAddress = new InternetAddress[recipients.length]; 
      InternetAddress[] toAddress = new InternetAddress[recipients.size()]; 
      for (int i = 0; i < recipients.size(); i++) { 
       toAddress[i] = new InternetAddress(recipients.get(i)); 
      } 
      msg.setRecipients(Message.RecipientType.TO, toAddress); 

      //set the subject and content type 
      msg.setSubject(emailSubject); 
      msg.setContent(actualMessage, "text/html; charset=utf-8"); 

      //send the email 
      Transport.send(msg); 

Исключение составляет, таким образом:

javax.mail.SendFailedException: Invalid Addresses; 
    nested exception is: 
    com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <[email protected]>: Sender address rejected: Access denied 

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1835) 
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1098) 
    at javax.mail.Transport.send0(Transport.java:195) 
    at javax.mail.Transport.send(Transport.java:124) 
    at internalLogicEngine.LogicEngine.sendReminder(LogicEngine.java:4282) 
    at testPackage.Test.main(Test.java:169) 
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <[email protected]>: Sender address rejected: Access denied 

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1733) 
    ... 5 more 

Любая помощь будет наиболее высокую оценку. Благодаря!

ответ

4

Наконец выяснили работу вокруг (хотя я до сих пор не могу понять, почему возникает проблема, в первую очередь, видя, как коды, используемые для работы. В любом случае ...)

private String outgoingMailServer = "smtp.mail.yahoo.com";  
boolean debug = false; 

//set the host outgoing mail smtp server. 
Properties properties = new Properties(); 
properties.put("mail.smtp.host", outgoingMailServer); 
properties.put("mail.smtps.auth", "true"); 

Authenticator authenticator = new SMTPAuthentication(); 
Session session = Session.getDefaultInstance(properties, authenticator); 
session.setDebug(debug); 

//create a message session 
Message msg = new MimeMessage(session); 

//set the addresses, to and from 
InternetAddress fromAddress; 
fromAddress = new InternetAddress(emailFromAddress); 
msg.setFrom(fromAddress); 

//since mail can be sent to more than one recipient, create loop 
//to add all addresses into InternetAddress, addressTo. 
//InternetAddress[] toAddress = new InternetAddress[recipients.length]; 
InternetAddress[] toAddress = new InternetAddress[recipients.size()]; 
for (int i = 0; i < recipients.size(); i++) { 
    toAddress[i] = new InternetAddress(recipients.get(i)); 
} 
msg.setRecipients(Message.RecipientType.TO, toAddress); 

//set the subject and content type 
msg.setSubject(emailSubject); 
msg.setContent(actualMessage, "text/html; charset=utf-8"); 

//send the email 
Transport transport = session.getTransport("smtps"); 
transport.connect(outgoingMailServer, 465, emailUserName, emailPassword); 
transport.sendMessage(msg, msg.getAllRecipients()); 
transport.close(); 

//email sent 
//note, this does not necessarily mean the email was delivered. The 
//sysetm has no control over that 
emailSent = true; 

You» Разыщу, что основное различие между кодами в вопросе, и эти из них являются:

Transport.send(msg); 

и

Transport transport = session.getTransport("smtps"); 
transport.connect(outgoingMailServer, 465, emailUserName, emailPassword); 
transport.sendMessage(msg, msg.getAllRecipients()); 
transport.close(); 

Оказывается, необходимо создать и подключить объект Transport с использованием соответствующих учетных данных (номер порта, имя пользователя, пароль и почтовый сервер).

Кроме того, я сделал процесс ликвидации и обнаружили, что до тех пор, пока у вас есть это:

Transport transport = session.getTransport("smtps"); 
transport.connect(outgoingMailServer, 465, emailUserName, emailPassword); 
transport.sendMessage(msg, msg.getAllRecipients()); 
transport.close(); 

вам это не нужно:

Authenticator authenticator = new SMTPAuthentication(); 
Session session = Session.getDefaultInstance(properties, authenticator); 

выше может также быть :

Session session = Session.getDefaultInstance(properties, null); 

В любом случае, это ответ. Вы также можете изменить этот ответ для gmail. Просто не забудьте изменить сервер исходящей почты на gmail, а также на адрес электронной почты, имя пользователя и пароль, и вы будете в порядке :)

Смежные вопросы