Java tutorial
/* Copyright 2006 - 2010 Under Dusken Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package no.dusken.common.control; import no.dusken.common.model.Mail; import no.dusken.common.util.MailSender; import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Required; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.ui.velocity.VelocityEngineUtils; import javax.mail.internet.MimeMessage; import java.util.HashMap; import java.util.Map; /** * @author Marvin B. Lillehaug <lillehau@underdusken.no> */ public class MailController implements MailSender { private JavaMailSender mailSender; private VelocityEngine velocityEngine; /** * If no other address is given, use this. */ private String defaultSenderAddress; /** * * @param mail the mail part of the mail * @param model other things that should be in the mail. * @param template - the path to the velocitytemplate to use (mail/template.vm) */ public void sendEmail(final Mail mail, final Map model, final String template) { final Map<String, Object> map = new HashMap<String, Object>(); if (model != null) { map.putAll(model); } MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(mail.getToAddress()); if (mail.getFromAddress() == null || mail.getFromAddress().equals("")) { mail.setFromAddress(defaultSenderAddress); } message.setFrom(mail.getFromAddress()); message.setSubject(mail.getSubject()); map.put("mail", mail); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map); message.setText(text, false); if (mail.getAttachment() != null) { FileSystemResource res = new FileSystemResource(mail.getAttachment()); message.addAttachment(mail.getAttachment().getName(), res); } } }; this.mailSender.send(preparator); } @Required public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } @Required public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } public void setDefaultSenderAddress(String defaultSenderAddress) { this.defaultSenderAddress = defaultSenderAddress; } }