求助:Spring MVC应用中基于Spring 4.3.6.RELEASE发送邮件遇问题
Hey there! I’ve got you covered with a full, working solution for sending emails in Spring 4.3.6.RELEASE—this should clear up those errors you’re running into. Let’s break it down step by step:
Complete Email Sending Solution for Spring 4.3.6.RELEASE
1. Dependency Setup (Maven Example)
First, make sure you have the right dependencies in your pom.xml—Spring 4.3.x relies on spring-context-support for email functionality, plus a compatible JavaMail API:
<dependencies> <!-- Spring Context Support for email handling --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.6.RELEASE</version> </dependency> <!-- JavaMail API (compatible with Spring 4.3.6) --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.6</version> </dependency> </dependencies>
2. Spring Configuration (XML Approach)
Create a dedicated spring-mail.xml or add these beans to your main Spring config file:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Core Mail Sender Bean --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.example.com"/> <!-- Replace with your SMTP server (e.g., smtp.gmail.com) --> <property name="port" value="587"/> <!-- Match your server's port (587 for TLS, 465 for SSL) --> <property name="username" value="your-email@example.com"/> <!-- Your email account --> <property name="password" value="your-app-specific-password"/> <!-- Use app password/authorization code for services like Gmail/QQ --> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> <!-- Required for TLS-enabled servers like Gmail --> <prop key="mail.smtp.connectiontimeout">5000</prop> <prop key="mail.smtp.timeout">5000</prop> </props> </property> </bean> <!-- Optional: Velocity Engine for HTML email templates --> <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> <property name="velocityProperties"> <props> <prop key="resource.loader">class</prop> <prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop> </props> </property> </bean> </beans>
3. Email Service Class
Wrap the email logic in a reusable service class for clean code organization:
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.ui.velocity.VelocityEngine; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.util.Map; public class EmailService { private JavaMailSender mailSender; private VelocityEngine velocityEngine; // Optional, for HTML templates // Setter injection (or use constructor injection if preferred) public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } // Send plain text email public void sendPlainTextEmail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); message.setFrom("your-email@example.com"); // Must match the username in your config mailSender.send(message); } // Send HTML email with Velocity template public void sendHtmlEmail(String to, String subject, Map<String, Object> templateData) throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setTo(to); helper.setSubject(subject); helper.setFrom("your-email@example.com"); // Render template (place your .vm file in src/main/resources/templates/) String htmlContent = velocityEngine.mergeTemplateIntoString("templates/email-template.vm", templateData); helper.setText(htmlContent, true); // Mark content as HTML mailSender.send(mimeMessage); } }
4. Register the Email Service in Spring
Add this bean to your Spring XML config to make the service available:
<bean id="emailService" class="com.yourpackage.EmailService"> <property name="mailSender" ref="mailSender"/> <property name="velocityEngine" ref="velocityEngine"/> <!-- Remove if you don't need HTML emails --> </bean>
5. Common Error Fixes
- SMTP Authentication Failed: Double-check your email credentials. For Gmail, enable 2FA and generate an app-specific password; for QQ mail, use the authorization code instead of your login password.
- Connection Timeouts: Verify your SMTP server address and port. For SSL (port 465), replace
starttls.enablewithmail.smtp.ssl.enable=truein thejavaMailProperties. - Version Compatibility: Stick with the JavaMail version (1.5.6) listed above—it’s tested to work with Spring 4.3.6.RELEASE.
Test the Service
Call the service from your application to verify it works:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashMap; import java.util.Map; public class EmailTest { public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("spring-mail.xml"); EmailService emailService = (EmailService) context.getBean("emailService"); // Send plain text email emailService.sendPlainTextEmail("recipient@example.com", "Spring 4.3.6 Test", "Hello from Spring email service!"); // Send HTML email (with template data) Map<String, Object> data = new HashMap<>(); data.put("userName", "Wahaj"); emailService.sendHtmlEmail("recipient@example.com", "HTML Test Email", data); } }
内容的提问来源于stack exchange,提问作者Wahaj Raza
相关产品推荐
相关产品推荐

