[Code] javaMail + spring + QQ email, javamailspring
1. Dependency: the spring version is modified according to the specific environment.
|
<Dependency>
<GroupId> javax. mail </groupId>
<ArtifactId> mail </artifactId>
<Version> 1.4 </version>
</Dependency>
<Dependency>
<GroupId> org. springframework </groupId>
<ArtifactId> spring-context-support </artifactId>
<Version >$ {spring. version} </version>
</Dependency> |
2. Configure spring
Use spring to manage and inject email objects
Note that port 587 is used instead of the legendary port 465. When port 465 is used to send emails, the program runs for a long time and cannot send emails.
|
<Bean id = "mailSender" class = "org. springframework. mail. javamail. JavaMailSenderImpl">
<! -- Inject the required elements -->
<! -- The email server uses QQ mail -->
<Property name = "host" value = "smtp.qq.com"/>
<! -- Sender email address -->
<Property name = "username" value = "XXXXXX@qq.com"/>
<! -- Send mail port -->
<Property name = "port" value = "587"/>
<! -- Password Use Authorization code -->
<Property name = "password" value = "XXXXXXXX"/>
<! ---->
<Property name = "javaMailProperties">
<Props>
<Prop key = "mail. smtp. host"> smtp.qq.com </prop>
<Prop key = "mail. transport. protocol"> smtp </prop>
<Prop key = "mail. smtp. auth"> true </prop>
</Props>
</Property>
</Bean> |
3. Write email sending code
|
// Inject the javaMailSender object before sending the email
@ Autowired
Private JavaMailSenderImpl mailSender; |
|
// Construct a simple email object
SimpleMailMessage smm = new SimpleMailMessage ();
// Set email Parameters
Smm. setFrom (mailSender. getUsername ());
// Set the recipient
Smm. setTo ("inbox @ qq.com ");
// Email Subject
Smm. setSubject ("this is a simple email ");
// Email content
Smm. setText ("Hello world via spring mail sender ");
// Send an email
MailSender. send (smm ); |