0

我将通过 spring 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

}

这是服务类

@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="mygmail@gmail.com" />
</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
mail.username=mygmail@gmail.com
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("mygmail@gmail.com"));
            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;
}

}

谢谢

4

2 回答 2

0

The autowired static fields in your controller may be the root cause of the issue. Try to update them as follows.

@Autowired
private UserService us;

@Autowired
private MailService mailService;

Also, how is the service's mailMessage field set?

于 2012-12-27T04:31:20.407 回答
0

嗨,问题已通过修复在 OS X 上运行 OpenJDK 7 时出现的 trustAnchors 问题得到解决

如果您在 OS X 上运行 OpenJDK 7 并看到此异常,则有一个简单的修复,只需链接到 Apple 的 JDK 1.6 使用的同一个 cacerts 文件:

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

于 2012-12-31T05:13:28.413 回答