当前位置: 首页 > 知识库问答 >
问题:

使用Spring MVC发送邮件

石苏燕
2023-03-14
@RequestMapping(value = "/SendMail"  )
    public ResponseEntity<String> SendMail( @RequestBody MailMessageDto mailDto)
            throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

问题是,当我更改Gateway和Transformmer方法签名以accomodate Multipart file和MailMessageDto时,我将在transform方法中将其转换为MimeMessageHelper对象,spring integration无法理解transform方法。

我想知道控制器方法的签名应该是什么,以及如何在XML中声明Transformer transform方法。

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 to authenticate to SMTP server -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- Use TLS to encrypt communication with 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>

The 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;


/**
 * The Class MailMessageTransformer.
 */
public class MailMessageTransformer {

/** The velocity engine. */
@Autowired
private VelocityEngine velocityEngine;

/** The mail sender. */
@Autowired
private JavaMailSender mailSender;

/** The Constant LOG. */
private static final Logger LOG = Logger.getLogger(MailMessageTransformer.class);



/**
* Transform MailMessageDto to SimpleMailMessage.
*
* @param mailDto the mail dto
* @return the 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 the email content/body using velocity engine, velocity template
* and MailMessageDto.
*
* @param mailDto the mail dto
* @return the 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 the Model Map referred in velocity mail template file.
*
* @param mailDto the mail dto
* @return the 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 the user (receients) name from MailMessageDto. This is referred in
* velocity template file. Currently from TO email list. Can be changed to
* look up user store if future
*
* @param toList the to list
* @return the user
*/
private String getUser(String[] toList) {

StringBuffer user = new StringBuffer();

for (String mailId : toList.clone()) {
StringTokenizer token = new StringTokenizer(mailId, IMailConstants.EMAIL_AT);
String to = token.nextToken();
user.append(to).append(IMailConstants.COMMA);
}

return user.toString();
}

/**
* Fetch the email type from MailMessageDto. This is referred in velocity
* template file.
*
* @param emailType the email type
* @return the 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 the name of velocity template file based on the emailType. Used by
* Velocity Engine.
*
* @param emailType the email type
* @return the 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 to MimeMessage.
*
* @param mailDto the mail dto
* @return the 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 the mail dto
*/

@Gateway
public void sendMail(MailMessageDto mailDto, MultipartFile file);

}

共有1个答案

张积厚
2023-03-14

第一:

@Gateway
public void sendMail(MailMessageDto mailDto, MultipartFile file);

第二:

public MimeMessage transform(MailMessageDto mailDto, final MultipartFile file) {

请仔细阅读Spring集成手册。

@Gateway
public void sendMail(MailMessageDto mailDto, @Header("file") MultipartFile file);
public MimeMessage transform(MailMessageDto mailDto, @Header("file") final MultipartFile file) {
 类似资料:
  • 本文向大家介绍springMVC发送邮件的简单实现,包括了springMVC发送邮件的简单实现的使用技巧和注意事项,需要的朋友参考一下 利用javax.mail发送邮件,图片与附件都可发送 1,Controller类 2,service类 MailModel实体类 spring.xml添加配置信息  dev.properties配置 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多

  • 我下载了Office 365 Connect ASP。NET MVC示例代码http://dev.office.com/code-samples-detail/5985,将其注册为Azure Active Directory中的应用程序(我具有全局管理员权限),并授予其所需的权限-“登录并读取用户配置文件”和“以用户身份发送邮件”(无其他权限),以及配置了web。配置为“ClientID”和“Cl

  • 我试图从域发送邮件,但得到一些错误。

  • 本文向大家介绍python3使用QQ邮箱发送邮件,包括了python3使用QQ邮箱发送邮件的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了python3使用QQ邮箱发邮件的具体代码,供大家参考,具体内容如下 直接上代码 如果登录失败可能是你的qq邮箱没有启动SMTP 解决: 启动后QQ会提供授权码,将代码中密码改为授权码即可。 成功后: 以上就是本文的全部内容,希望对大家的学习有所帮

  • 问题内容: 如何使用curl命令行程序从gmail帐户发送电子邮件? 我尝试了以下方法: 使用file.txt作为电子邮件的内容,但是,当我运行此命令时,出现以下错误: 是否可以从仍由curl托管的个人服务器托管帐户发送电子邮件?这样会使身份验证过程更容易吗? 问题答案: curl –url 'smtps://smtp.gmail.com:465’ –ssl-reqd \ –mail-from '

  • 问题内容: 我正在尝试使用Java发送电子邮件: 我收到错误消息: 此代码可以发送电子邮件吗? 问题答案: 户名+密码不再是推荐的解决方案。这是因为 我尝试了此操作,Gmail向该代码中用作用户名的电子邮件发送了一封电子邮件,其中说我们最近阻止了你的Google帐户的登录尝试,并将我定向到此支持页面:support.google.com/accounts/answer/6010255因此它看起来很