2012-12-27 96 views
0

我會通過彈簧mvc發送電子郵件,但我得到下面的錯誤。爲什麼不能通過彈簧發送電子郵件mvc

感謝您的幫助。

java.lang.ClassCastException: service.MailService$1 cannot be cast to org.springframework.mail.SimpleMailMessage 
at service.MailService.sendEmail(MailService.java:69) 
at sendPasswordToUser(SendPasswordController.java:44) 

我的代碼是:

public class EmailMessage 
    { 

private String receiverEmailAddress; 
private String subject; 
private String messageBody; 

public EmailMessage() 
{ 
} 
    //+setters and getters 

} 

這是服務CALSS

@Service 
public class EmailSenderService implements EmailSenderRepository 
{ 

private MailSender mailSender; 
private SimpleMailMessage mailMessage; 

public void setMailMessage(SimpleMailMessage mailMessage) { 
this.mailMessage = mailMessage; 
} 

public void setMailSender(MailSender mailSender) { 
    this.mailSender = mailSender; 
} 

public void sendEmail(EmailMessage emailMessage) 
{ 
    SimpleMailMessage message = new SimpleMailMessage(this.mailMessage); 

    message.setTo(emailMessage.getReceiverEmailAddress()); 
    message.setSubject(emailMessage.getSubject()); 
    message.setText(emailMessage.getMessageBody()); 
    //sending the message 
    mailSender.send(message); 

} 

} 

而且控制器:

@Controller 
@RequestMapping 
public class SendPasswordController 
{ 

@Autowired 
private static UserService us = new UserService(); 
@Autowired 
private static MailService mailService = new MailService(); 

@RequestMapping(value = "/getPassword", method = RequestMethod.GET) 
public String showForm() 
{ 

    return "index"; 
} 

@RequestMapping(value = "sendPassword", method = RequestMethod.POST) 
public String sendPasswordToUser(@RequestParam("email") String email, ModelMap model, HttpServletRequest req, HttpServletResponse response) 
{ 
    String subject = "Sending your password to you "; 

    User user = us.findUserByAnyParameter(email); 

    if (email.equals(user.getEmail())) 
    { 
     mailService.sendEmail(user.getPassword(), subject, email); 
     model.addAttribute("message", user); 

     return "confirmNewPassword"; 
    } 
    else 
    { 
     return "redirect:/index"; 

    } 

} 

} 

JSP頁面是:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1" import="java.util.*" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd"> 
<html lang="en"> 
<head> 
<meta charset="utf-8" /> 
<title>Log In</title> 
<link href="<%=request.getContextPath()%>/resources/css/layout.css" 
rel="stylesheet" type="text/css" /> 
<link href="<%=request.getContextPath()%>/resources/css/menu.css" 
rel="stylesheet" type="text/css" /> 
<link href="<%=request.getContextPath()%>/resources/css/styles.css" 
rel="stylesheet" type="text/css" /> 


</head> 
<body> 


    <c:if test="${not empty error}"> 
    <div class="errorblock"> 
     Your login attempt was not successful, try again.<br /> Caused : 
     ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} 
    </div> 
</c:if> 

    <div id="formContainer"> 
     <form id="login" method="post" action="<c:url value='j_spring_security_check' />"> 
      <a href="<c:url value="http://localhost:8080/guard_weblayer/getPassword/" /> id="flipToRecover" class="flipLink">Forgot?</a> 
       <input type="text" name="j_username" id="loginUsername" required="required" maxlength="45" placeholder="username" /> 
       <input type="password" name="j_password" id="loginPass" required="required" maxlength="45" placeholder="pass"/> 
       <input type="submit" name="submit" value="Login" /> 
     </form> 
     <form id="recover" method="post" action="sendPassword"> 
      <a href="<c:url value="http://localhost:8080/guard_weblayer/getPassword/" /> id="flipToLogin" class="flipLink">Forgot?</a> 
      <input type="text" name="email" id="recoverEmail" required="required" maxlength="45" placeholder="mail" /> 
      <input type="submit" name="submit" value="Recover" onClick="window.location='confirmNewPassword';" /> 
     </form> 
    </div> 



    <!-- JavaScript includes --> 
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
    <script src="<%=request.getContextPath()%>/resources/js/script.js"></script> 
</div> 

和emailConfiguration.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
    <property name="host" value="${mail.host}" /> 
    <property name="username" value="${mail.username}" /> 
    <property name="password" value="${mail.password}" /> 
    <property name="port" value="${mail.port}" /> 
    <property name="protocol" value="smtp" /> 

    <property name="javaMailProperties"> 
     <props> 
      <prop key="mail.smtp.auth">${mail.smtp.auth}</prop> 
      <prop key="mail.smtp.connectiontimeout">5000</prop> 
      <prop key="mail.smtp.sendpartial">${mail.smtp.sendpartial}</prop> 
      <prop key="mail.smtp.userset">${mail.smtp.userset}</prop> 
      <prop key="mail.mime.charset">UTF-8</prop> 
      <prop key="mail.smtp.isSecure">${mail.smtp.isSecure}</prop> 
      <prop key="mail.smtp.requiresAuthentication">${mail.smtp.requiresAuthentication}</prop> 
      <prop key="mail.smtps.auth">${mail.smtps.auth}</prop> 
      <prop key="mail.smtp.port">${mail.port}</prop> 
      <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> 
      <prop key="mail.smtp.socketFactory.fallback">${mail.smtp.socketFactory.fallback}</prop> 
      <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop> 
      <prop key="mail.debug">${mail.debug}</prop> 
     </props> 
    </property> 
</bean> 

<bean id="messageTemplate" class="org.springframework.mail.SimpleMailMessage" 
    scope="prototype"> 
    <property name="from" value="[email protected]" /> 
</bean> 

<!-- <bean id="emailSenderBean" class="org.convey.example.email.EmailSender"> --> 
<!-- <property name="mailSender" ref="mailSender" /> --> 
<!-- </bean> --> 
</beans> 

和mail.properties

mail.host=smtp.gmail.com 
mail.port=465 
mail.protocol= smtps 
[email protected] 
mail.password=************ 
mail.transport.protocol=smtp 
mail.smtp.auth=true 
mail.smtp.starttls.enable=true 
mail.debug=true 
mail.smtps.host=true 
mail.smtps.auth=true 
mail.smtp.isSecure=true 
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory 
mail.smtp.socketFactory.fallback=false 
mail.smtp.requiresAuthentication=true 
mail.smtp.userset=true 
mail.smtp.sendpartial=true 

這裏是服務類:

public class MailService implements MailRepository 
{ 
@Autowired 
private MailSender mailSender; 
@Autowired 
private SimpleMailMessage messageTemplate; 
@Autowired 
private JavaMailSender javamailSender; 

public void setMailSender(JavaMailSender mailSender) 
{ 
    this.mailSender = mailSender; 
} 


public void sendMail(String mailFrom, String mailTo, String subject, String mailBody) 
{ 
    SimpleMailMessage message = new SimpleMailMessage(this.messageTemplate); 
    message.setFrom(mailFrom); 
    message.setTo(mailTo); 
    message.setText(mailFrom + mailTo + mailBody); 
    this.mailSender.send(message); 

} 

public void sendEmail(EmailMessage emailMessage) 
{ 
    SimpleMailMessage message = new SimpleMailMessage(this.messageTemplate); 

    message.setTo(emailMessage.getReceiverEmailAddress()); 
    message.setSubject(emailMessage.getSubject()); 
    message.setText(emailMessage.getMessageBody()); 
    // sending the message 
    this.mailSender.send(message); 
} 

public boolean sendEmail(final String message, final String subject, final String emailAddress) 
{ 
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    { 

     public void prepare(MimeMessage mimeMessage) throws Exception 
     { 

      mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); 
      mimeMessage.setFrom(new InternetAddress("[email protected]")); 
      mimeMessage.setText(message, "ISO-8859-1"); 
      mimeMessage.setSubject(subject, "ISO-8859-1"); 
     } 
    }; 

    try 
    { 
     this.mailSender.send((SimpleMailMessage) preparator); 
    } 
    catch (Exception ex) 
    { 
     ex.printStackTrace(); 
     return false; 
    } 

    return true; 
} 

} 

謝謝

回答

0

控制器中的自動編排的static字段可能是問題的根本原因。嘗試按照以下方式更新它們。

@Autowired 
private UserService us; 

@Autowired 
private MailService mailService; 

此外,該服務的mailMessage字段如何設置?

+0

嗨 我也編輯我的問題。 它不工作我得到了一個404.I用戶MailService類,正如你所看到的,我有幾種發送電子郵件的方法,但其中沒有一個正在工作。 – user1067665

+0

您的@RequestMapping缺少一個斜槓,它應該是「/ sendPassword」。 – izilotti

+0

但這不是問題。任何人都可以幫助 – user1067665

0

嗨的問題是通過固定在OS X上運行的OpenJDK 7時trustAnchors問題解決

如果你在OS X上運行的OpenJDK 7和看到這個異常 有一個簡單的解決,只是在鏈接同樣cacerts文件,蘋果公司的JDK 1.6用途:

cd $(/usr/libexec/java_home -v 1.7)/jre/lib/security 
ln -fsh /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts 

欲瞭解更多信息,請參見下面的鏈接:

http://architecturalatrocities.com/post/19073788679/fixing-the-trustanchors-problem-when-running-openjdk-7