How To send Email with attachment in java with spring

1-add Emailtemplate.vm to class path of java i mean src/main/java

<html>
<body>
<h3 >${subject} </h3>
<div>   ${messageBody} </div>
<h3>File ID=${FileID}    <br> Provider ID=${ProviderID}
</h3>
</body>
</html>

2-then add dependency in pom file for volicity


<dependency>
<groupId>maven</groupId>
<artifactId>velocity</artifactId>
<version>1.5-20060721.044818</version>
<exclusions>
<exclusion>
<groupId>geronimo-spec</groupId>
<artifactId>geronimo-spec-javamail</artifactId>

</exclusion>

<exclusion>
<groupId>geronimo-spec</groupId>
<artifactId>geronimo-spec-jms</artifactId>

</exclusion>

</exclusions>
</dependency>

3- add bean in root context for java mail sender and one also for volicity
<!–email sender –>
<bean id=”mailSender”
p:host=”mail.bookdepository.co.uk” p:port=”27″>

<property name=”username” value=”shady.ragab” />
<property name=”password” value=”User2010″ />

</bean>

<!– velocity template –>
<bean id=”velocityEngine”
class=”org.springframework.ui.velocity.VelocityEngineFactoryBean”>
<property name=”velocityProperties”>
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>

4- service

@Service
public class MailServiceImpl implements MailService {

	@Autowired
	JavaMailSender mailSender;
	@Autowired
	VelocityEngine velocityEngine;

	public void send(final String from, final String[] to, final String[] cc, final String[] bcc,

			final String subject, final String messageBody,final NotificationBean notification)

			throws MessagingException {

		  final MimeMessagePreparator preparator = new MimeMessagePreparator()
		  {
		         public void prepare(MimeMessage mimeMessage) throws Exception {
		            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);
		            message.setSubject(subject);
		            message.setTo(to);
		            message.setFrom(from); // could be parameterized...
		            message.setBcc(bcc);
		            message.setCc(cc);
		            Map model = new HashMap();
		            model.put("subject",subject);
		            model.put("messageBody",messageBody);

		            Listtemp= (List) notification.getNotificationParamsCollection();
		            for (NotificationParam param : temp) {
		            	System.out.println(param.getId().getKey()+"  "+ param.getValue());
				    if(param.getId().getKey().equals("File ID"))
					     model.put("FileID",param.getValue());
					 if(param.getId().getKey().equals("Provider ID"))
						  model.put("ProviderID",param.getValue());

					}

		            String text = VelocityEngineUtils.mergeTemplateIntoString(
				               velocityEngine, new ClassPathResource("Emailtemplate.vm").getPath(), model);
		            message.setText(text, true);

		            byte[]attachdata="this is testing file".getBytes();
		            InputStreamSource source= new ByteArrayResource(attachdata);
		            message.addAttachment("test.txt", source,"text/plain");
		            /*if(notification.getAttachmentFileName()!=null){
		            message.addAttachment(notification.getAttachmentFileName().concat(notification.getMimeType().getExtension()),
		            		new ByteArrayDataSource(notification.getAttachment(), notification.getMimeType().getMimeType()));
		            }*/

		         }
		      };

		      new Thread(){
		    	  public void run(){
		    		  mailSender.send(preparator);
		    	  }
		      }.start();

	}

}
Advertisements

About lorddisk

WebCenter Content, WebCenter Portal, WebCenter Sites,Weblogic, Identity and Access Management (IAM),SSO,OAM,OIM,OAAM,OUD, OPAM,OID, OVD ,Oracle API Gateway ,OBIEE,OEDQ, Oracle ADF, Oracle SOA,J2EE, CackePHP ,PHP,J2SE,J2EE,Spring,Hibernate,JQuery,CSS,Java Script ,Joomla,Drupal,Worpress
This entry was posted in java, spring and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s