Send Mail using Spring MVC -


i have custom maildto object in set to,cc, bcc field , send using resttemplate spring mvc controller below

@requestmapping(value = "/sendmail"  )     public responseentity<string> sendmail( @requestbody mailmessagedto maildto)             throws nosuchmethodexception, illegalaccessexception, illegalargumentexception, invocationtargetexception 

from controller invoke gateway (spring integration). gateway has method public void sendmail(mailmessagedto maildto). gateway channel invokes transformer converts maildto mimemessagehelper object. mimemessagehelper object sent mail using mailoutbound adapter. want send mail using resttemplate attachment using same maildto.

problem when changing the gateway , transformmer method signature accomodate multipart file , mailmessagedto convert mimemessagehelper object in transform method spring integration not able understand transform method.

i wondering should signature of controller method , how declare transformer transform method in xml.

the mail-context file <context:component-scan base-package="com.infra.mail,com.infra.audit " />       <mvc:annotation-driven />        <!-- <context:property-placeholder  location="classpath:/mail.properties" ignore-unresolvable="true" /> -->      <bean id="mailsender" class="org.springframework.mail.javamail.javamailsenderimpl">         <property name="host" value="${mail.host}"/>         <property name="port" value="${mail.port}"/>         <property name="username" value="${mail.username}"/>         <property name="password" value="${mail.password}"/>         <property name="defaultencoding" value="utf-8"/>          <property name="javamailproperties">             <props>                 <!-- use smtp transport protocol -->                 <prop key="mail.transport.protocol">smtp</prop>                 <!-- use smtp-auth authenticate smtp server -->                 <prop key="mail.smtp.auth">true</prop>                 <!-- use tls encrypt communication smtp server -->                 <prop key="mail.smtp.starttls.enable">false</prop>                 <prop key="mail.debug">true</prop>             </props>         </property>     </bean>          <int:channel id="xfrommailchannel">     <int:queue/>      </int:channel>  transformer file  import java.util.arraylist; import java.util.date; import java.util.hashmap; import java.util.list; import java.util.map; import java.util.stringtokenizer;  import javax.mail.messagingexception; import javax.mail.internet.mimemessage;  import org.apache.log4j.logger; import org.apache.velocity.app.velocityengine; import org.springframework.beans.factory.annotation.autowired; import org.springframework.mail.mailexception; import org.springframework.mail.mailmessage; import org.springframework.mail.simplemailmessage; import org.springframework.mail.javamail.javamailsender; import org.springframework.mail.javamail.mimemessagehelper; import org.springframework.ui.velocity.velocityengineutils;   /**  * class mailmessagetransformer.  */ public class mailmessagetransformer {  /** velocity engine. */ @autowired private velocityengine velocityengine;  /** mail sender. */ @autowired private javamailsender mailsender;  /** constant log. */ private static final logger log = logger.getlogger(mailmessagetransformer.class);    /** * transform mailmessagedto simplemailmessage. * * @param maildto mail dto * @return mail message */ public mailmessage transformsimple(mailmessagedto maildto) {  log.debug("mailmessagetransformer.transform.mailmessagedto:::" + maildto); if (maildto == null) { return null; }  if (maildto.getencoding() == null) { maildto.setencoding(imailconstants.default_encoding); }  if (maildto.gettemplatename() == null || !maildto.gettemplatename().endswith(imailconstants.velocity_template_extn)) { maildto.settemplatename(gettemplatename(maildto.getemailtype())); }  simplemailmessage message = new simplemailmessage();  message.setfrom(maildto.getfrom()); message.setto(maildto.getto()); message.setsubject(maildto.getsubject()); message.settext(getmailcontent(maildto)); message.setsentdate(new date(system.currenttimemillis()));  message.setbcc(maildto.getbcc()); message.setcc(maildto.getcc()); message.setreplyto(maildto.getreplyto());  /* * if (null != maildto.getbcc()) { message.setbcc(maildto.getbcc()); } * if (null != maildto.getbcc()) { message.setcc(maildto.getcc()); } if * (null != maildto.getreplyto() && !maildto.getreplyto().isempty()) { * message.setreplyto(maildto.getreplyto()); } */  log.debug("mailmessagetransformer.transform.message:::" + message); return message; }  /** * create email content/body using velocity engine, velocity template * , mailmessagedto. * * @param maildto mail dto * @return mail content */ private string getmailcontent(mailmessagedto maildto) { map<string, object> model = getvelocitymodel(maildto); string mailcontent = velocityengineutils.mergetemplateintostring(velocityengine, maildto.gettemplatename(), maildto.getencoding(), model); log.debug("mailmessagetransformer.getmailcontent.mailcontent:::" + mailcontent); return mailcontent; }  /** * create model map referred in velocity mail template file. * * @param maildto mail dto * @return velocity model */ private map<string, object> getvelocitymodel(mailmessagedto maildto) { map<string, object> model = new hashmap<string, object>(); model.put(imailconstants.vm_user, getuser(maildto.getto())); model.put(imailconstants.vm_alert_type, getalerttype(maildto.getemailtype())); model.put(imailconstants.vm_content, maildto.gettext()); return model; }  /** * fetch user (receients) name mailmessagedto. referred in * velocity template file. email list. can changed * user store if future * * @param tolist list * @return user */ private string getuser(string[] tolist) {  stringbuffer user = new stringbuffer();  (string mailid : tolist.clone()) { stringtokenizer token = new stringtokenizer(mailid, imailconstants.email_at); string = token.nexttoken(); user.append(to).append(imailconstants.comma); }  return user.tostring(); }  /** * fetch email type mailmessagedto. referred in velocity * template file. * * @param emailtype email type * @return alert type */ private string getalerttype(string emailtype) {  string alerttype = imailconstants.system_alert_text;  if (imailconstants.realtime_emailtype.equalsignorecase(emailtype)) { alerttype = imailconstants.realtime_alert_text; } else if (imailconstants.offline_emailtype.equalsignorecase(emailtype)) { alerttype = imailconstants.offline_alert_text; }  return alerttype; }  /** * fetch name of velocity template file based on emailtype. used * velocity engine. * * @param emailtype email type * @return template name */ private string gettemplatename(string emailtype) {  string templatename = imailconstants.system_alert_vm; if (imailconstants.realtime_emailtype.equalsignorecase(emailtype)) { templatename = imailconstants.realtime_alert_vm; } else if (imailconstants.offline_emailtype.equalsignorecase(emailtype)) { templatename = imailconstants.offline_alert_vm; } return templatename; }   /** * transform mailmessagedto mimemessage. * * @param maildto mail dto * @return mime message */ //public mimemessage transform(final mailmessagedto maildto,final commonsmultipartfile file) {  public mimemessage transform(mailmessagedto maildto, final multipartfile file) {    log.debug("mailmessagetransformer.transform.maildto:::" + maildto);  if (maildto == null) { return null; }  if (maildto.getencoding() == null) { maildto.setencoding(imailconstants.default_encoding); }  if (maildto.gettemplatename() == null || !maildto.gettemplatename().endswith(imailconstants.velocity_template_extn)) { maildto.settemplatename(gettemplatename(maildto.getemailtype())); }  maildto.settext(maildto.gettext().replaceall(system.lineseparator(), imailconstants.html_new_line));  mimemessage mimemessage = null; try { string attachname = file.getoriginalfilename(); mimemessage = mailsender.createmimemessage(); mimemessagehelper message = new mimemessagehelper(mimemessage); message.setto(maildto.getto()); message.setfrom(maildto.getfrom()); message.setsubject(maildto.getsubject()); message.settext(getmailcontent(maildto), imailconstants.true); message.setsentdate(new date(system.currenttimemillis())); message.addattachment(attachname, new inputstreamsource() {                 @override                public inputstream getinputstream() throws ioexception {                    return file.getinputstream();                }            });   if (null != maildto.getbcc()) { message.setbcc(maildto.getbcc()); } if (null != maildto.getbcc()) { message.setcc(maildto.getcc()); } if (null != maildto.getreplyto() && !maildto.getreplyto().isempty()) { message.setreplyto(maildto.getreplyto()); }  } catch (messagingexception msgex) { log.error("mailmessagetransformer.transformmime.exception::: messagingexception", msgex);  } catch (mailexception mailex) { log.error("mailmessagetransformer.transformmime.exception::: mailexception ", mailex);  }  catch (exception ex) { log.error("mailmessagetransformer.transformmime.exception::: exception", ex);  }  log.debug("mailmessagetransformer.transformmime.mimemessage:::" + mimemessage); return mimemessage; }  }     <int:channel id="outboundmailchannel"/>    <int:channel id="confirmationchannel"/>       <int:gateway id="mailgateway" service-interface="com.infra.mail.mailgateway"       default-request-channel="xfrommailchannel" default-reply-channel="confirmationchannel" error-channel="errorchannel">       <int:method name="sendmail" payload-expression="#args[0] + #args[1]"> </int:method>       </int:gateway>        <int:transformer input-channel="xfrommailchannel" output-channel="outboundmailchannel"       ref="mailtransformer" method="transform">         <int:poller fixed-rate="60000" max-messages-per-poll="100"/>    </int:transformer>     <!-- configure mail sender -->    <int-mail:outbound-channel-adapter channel="outboundmailchannel" mail-sender="mailsender"/>     <bean id="mailmessage" scope="prototype">       <property name="from" value="${mail.user2}"/>       <property name="replyto" value="${mail.user3}"/>    </bean>     <bean id="mailtransformer" class="com.infra.mail.mailmessagetransformer"/>  </bean>    <int:service-activator id="mailerrorchannelactivator" input-channel="errorchannel" ref="errorhandler" method="handlemailerror"/>     <bean id="errorhandler" class="com.infra.audit.errorhandler"/>    <int:channel-interceptor ref="infrainterceptor" pattern="*" order="3"/>   <bean id="infrainterceptor" class="com.infra.audit.infrainterceptor"/>       <int:channel id="sftperrorchannel" />    <int:chain input-channel="xfrommailchannel" output-channel="outboundmailchannel"> <int:header-enricher> <int:error-channel ref="errorchannel" /> </int:header-enricher> <int:poller fixed-rate="6000" max-messages-per-poll="1"/>  </int:chain>  **the gateway file** public interface mailgateway {  /** * send mail. * * @param maildto mail dto */  @gateway public void sendmail(mailmessagedto maildto, multipartfile file);  } 

first:

@gateway public void sendmail(mailmessagedto maildto, multipartfile file); 

second:

public mimemessage transform(mailmessagedto maildto, final multipartfile file) { 

please, read spring integration manual closely.

so, should understand here spring integration (and messaging) gets deal message. honor framework allows use pojo method-invocation style interaction, should follow here simple rules.

only 1 method argument payload. yes, in places @publisher can use spel @payload value build payload several arguments, in general 1 of them can payload: or 1 marked @payload, or 1 isn't map<string, object> treated messageheaders.

you may not mark @payload must similar others - mark them @header.

so, fix issue should this:

@gateway public void sendmail(mailmessagedto maildto, @header("file") multipartfile file); 

and:

public mimemessage transform(mailmessagedto maildto, @header("file") final multipartfile file) { 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -