Spring boot + activeMq mail Service

Source: Internet
Author: User

Introduce dependencies:

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId> spring-boot-starter-activemq</artifactid>        </dependency>        <dependency>            <groupid >org.springframework.boot</groupId>            <artifactId>spring-boot-starter-mail</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-freemarker</artifactId>        </dependency>

Configuration file:

Spring:activemq:broker-URL:TCP://127.0.0.1:61616In-memory:truepool:enabled:falsemail:host:smtp.163. com username: Your mailbox password: Your password properties:mail:smtp:truestarttls:enable:trueRequired:trueFreemarker:allow-request-override:falseCache:trueCheck-template-location:trueCharset:utf-8content-type:text/HTML Expose-request-attributes:falseExpose-session-attributes:falseExpose-spring-macro-helpers:falsemail:fromMail:addr: [email protected]163.com

Mail Service:

 Public Interface Mailservice {    boolean  sendEmail (string to, string subject, string content);     boolean sendemailbytemplate (string to, string subject, String templatefile, map<string, string>  content);}
@Service Public classMailserviceimplImplementsMailservice {@AutowiredPrivateJavamailsender MailSender; @Value ("${mail.frommail.addr}")    PrivateString from;//Mail Sender@Override Public BooleanSendEmail (string to, string subject, string content) {MimeMessage message=Mailsender.createmimemessage (); Mimemessagehelper Helper=Newmimemessagehelper (message); Try{helper.setfrom (from);//Mail SenderHelper.setto (to);//Mail RecipientHelper.setsubject (subject);//Message SubjectHelper.settext (Content,true);//message body, whether HTML format is supportedMailsender.send (message);//Send mail}Catch(messagingexception e) {e.printstacktrace (); return false; }        return true; } @Override Public BooleanSendemailbytemplate (string to, string subject, String templatefile, Map<string, string>content) {Configuration cfg=NewConfiguration (configuration.version_2_3_23); Cfg.setclassfortemplateloading ( This. GetClass (), "/templates"); Try{Template Template=cfg.gettemplate (templatefile); String HTML=freemarkertemplateutils.processtemplateintostring (template, content); return  This. SendEmail (To, subject, HTML); } Catch(Exception e) {e.printstacktrace (); return false; }    }}

Template file:

Spring Boot startup class:

@SpringBootApplication @enablejms  Public class Application {    @Bean ("Emailqueue")    public  Queue emailqueue () {         return New Activemqqueue ("Email.queue");    }      Public Static void Main (string[] args) {        springapplication.run (application. class , args);}    }

Email Rest Interface:

/*** e-mail Service exposed to external rest interface*/@RestController @requestmapping ("/mail") Public classMailrestcontroller {@AutowiredPrivateMailproducer Mailproducer; /*** Send Simple Mail message cache in ACTIVEMQ queue*/@PostMapping ("/send")     Publicstring Send (@RequestParam string to, @RequestParam string subject, @Reque Stparam String content) {Map<string, string> map =NewHashmap<>(); Map.put ("To", to); Map.put ("Subject", subject); Map.put ("Content", content); String msg=jsonobject.tojsonstring (map);        Mailproducer.send (msg); return"Success"; }}

By requesting the/test/send interface, the message information that you want to send is cached in the email.queue queue of ACTIVEMQ by invoking the mail message producer.

Send mail by mail message consumer calling Mail service class

Mail message producers:

/***/@Componentpublicclass  mailproducer {    @Autowired     Private jmsmessagingtemplate jmsmessagingtemplate;    @Autowired    @Qualifier ("Emailqueue")    private  Queue emailqueue;      Public void Send (String msg) {        this. Jmsmessagingtemplate.convertandsend. Emailqueue, msg);    }    }

Mail Message consumer:

/*** Mail Message consumer*/@Component Public classMailconsumer {@AutowiredPrivateMailservice Mailservice; @JmsListener (Destination= "Email.queue")     Public voidreceivequeue (String text) {System.out.println ("Consumer mail message:" +text); //send mail messages from the ACTIVEMQ email.queue queue to the recipient's mailboxJsonobject Jsonobject =jsonobject.parseobject (text); String to= Jsonobject.getstring ("to"); String subject= Jsonobject.getstring ("Subject"); String content= jsonobject.getstring ("Content");    Mailservice.sendemail (to, subject, content); }    }

To start the project test interface:

Send a POST request

The initial call interface will report this error: The mailbox is not available 550 User has no permission

You can refer to this article to solve the problem: 52070878

Mailbox unavailable 550 User has no permissionJuly 30, 2016 09:18:43Hits: 17974

When the correct user name and password are sent to the sending mailbox, always receive the error: 550 user has no permission,

In fact, when we send mail in Java, we use the custom client to log in based on the user name and password, and then send the message using the SMTP service. However, the newly registered 163 messages are not turned on by default for Client authorization verification (default on for custom mailbox master clients),

Therefore the login is always rejected, and authentication does not have permissions. The solution is to enter 163 mailbox, enter the mailbox center-the client authorization password, choose to open, as follows

After the setup is complete, use the client authorization password in your code instead of the original mailbox password, so that you can send the message correctly.

Continue sending the POST request, observe the results

E-Mail Received:

Spring boot + activeMq mail Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.