Подтвердить что ты не робот

Как отправить HTML-адрес электронной почты в Spring MVC?

Я успешно отправил простую электронную почту, используя это:

SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo("[email protected]");
mailMessage.setSubject("This is the test message for testing gmail smtp server using spring mail");
mailMessage.setFrom("[email protected]");
mailMessage.setText("This is the test message for testing gmail smtp server using spring mail. \n" +
        "Thanks \n Regards \n Saurabh ");
mailSender.send(mailMessage);

Какую настройку мне нужно выполнить, чтобы я мог отправлять html-письма

4b9b3361

Ответ 1

Я не думаю, что класс SimpleMailMessage имеет такие параметры.

Я уверен, что вы можете сделать это с помощью JavaMailSender и MimeMessagePreparator, потому что вам нужно установить тип содержимого MIME для HTML.

См. эту ссылку для справки:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mail.html

Ответ 2

import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.MimeMessageHelper;

MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8");
String htmlMsg = "<h3>Hello World!</h3>";
//mimeMessage.setContent(htmlMsg, "text/html"); /** Use this or below line **/
helper.setText(htmlMsg, true); // Use this or above line.
helper.setTo("[email protected]");
helper.setSubject("This is the test message for testing gmail smtp server using spring mail");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);

Ответ 3

В Spring это должно быть сделано следующим образом:

Ваш класс электронной почты:

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class HTMLMail
{
    private JavaMailSender mailSender;


    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String from, String to, String subject, String msg) {
        try {

            MimeMessage message = mailSender.createMimeMessage();

            message.setSubject(subject);
            MimeMessageHelper helper;
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setText(msg, true);
            mailSender.send(message);
        } catch (MessagingException ex) {
            Logger.getLogger(HTMLMail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}

beans: (Spring -Mail.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />
        <property name="port" value="587" />
        <property name="username" value="[email protected]" />
        <property name="password" value="yourpassword" />

        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>
    <bean id="htmlMail" class="com.mohi.common.HTMLMail">
        <property name="mailSender" ref="mailSender" />
    </bean>
</beans>

Применение:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Mail.xml");

        HTMLMail mm = (HTMLMail) context.getBean("htmlMail");
        String html="<p>Hi!</p><a href=\"google.com\">Link text</a>";
    mm.sendMail("[email protected]",
            "[email protected]",
            "test html email",
            html);

Полный пример здесь.

Ответ 4

Вам может быть интересно проверить эту статью: "Богатый HTML-адрес электронной почты в Spring с Thymeleaf" http://www.thymeleaf.org/doc/articles/springmail.html

Он использует Тимелеаф в качестве шаблонного уровня представления, но понятия и Spring -специфический код, объясненный там, являются общими для всех приложений Spring.

Кроме того, у него есть приложение-пример сопутствующего приложения, исходный код которого вы можете использовать в качестве базы для ваших нужд.

С уважением, Daniel.

Ответ 5

Уровень класса:

public String sendEmailToUsers(String emailId,String subject, String name){
    String result =null;
    MimeMessage message =mailSender.createMimeMessage();
    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body style='border:2px solid black'>"
                    +"Your onetime password for registration is  " 
                        + "Please use this OTP to complete your new user registration."+
                          "OTP is confidential, do not share this  with anyone.</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }

    return result;

}

Уровень XML:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="********@gmail.com" />
    <property name="password" value="********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

Ответ 6

String emailMessage = report.toString();
            Map velocityContext = new HashMap();
            velocityContext.put("firstName", "messi");
            velocityContext.put("Date",date );  
            velocityContext.put("Exception",emailMessage );
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "VelocityTemplate.vm","UTF-8", velocityContext);
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper;
            helper = new MimeMessageHelper(message, true);
            helper.setTo("[email protected]gmail.com");
            helper.setFrom("[email protected]");
            helper.setSubject("new email");
            helper.setText(text, true);         
            mailSender.send(message);

Ответ 7

DVController.java

package com.dv;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;

@RestController
public class DVController {

 //Autowired Configuration class to get instance
 @Autowired
    private Configuration freemarkerConfig;

 private static Logger logger = LoggerFactory.getLogger(DVController.class);

 private String host = "SMTP sever address";
 private Integer port = SMTP server port number;
 private String userName = "Your user name";
 private String password = "Your account password";

 public Session createSMTPServerSession() throws Exception {

  Properties props = new Properties();
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", port);
  props.put("mail.smtp.auth", "true");

  // SSL SECURITIES CERTIFICATION
  props.put("mail.smtp.startssl.enable", "true");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.setProperty("mail.smtp.ssl.enable", "true");
  props.setProperty("mail.smtp.ssl.required", "true");

  // Create the connection session after authentication
  Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(userName, password);
   }
  });
  return session;
 }

 @RequestMapping(method=RequestMethod.GET,value="sendemail")
 public boolean sentMail() throws Exception {

  //Get session connection 
  Session session = createSMTPServerSession();

  //Create MimeMessage instance for communication
  MimeMessage message = new MimeMessage(session);

  //Set User Name in which id the email sent to client 
  message.setFrom(new InternetAddress(userName));

  //Get the instance from autowired variable and load the template in instance and set the path where ftl file available
  freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/freemarker");

  //Create a map object and set the data which is send dynamically to the FTL template file
  Map<String, String> ftlProperties = new HashMap<String,String>();
  ftlProperties.put("header", "DEVELOPER VILLAGE");
  ftlProperties.put("userName", "Developer village");
  ftlProperties.put("message", "This is the testing ftl from message developer village email.");

  //Instance the FTL file with the name
  Template t = freemarkerConfig.getTemplate("developer_village.ftl");

  //Set the FTL properties
  String text = FreeMarkerTemplateUtils.processTemplateIntoString(t,ftlProperties);


  message.addRecipient(Message.RecipientType.TO, new InternetAddress("Write the email address,want to send email"));

  //Set the email type in this case it html syntax
  message.setContent(text, "text/html");

  //Set the email header
  message.setSubject("Testing email from Developer Village.");
  Transport.send(message);

  return true;
 }
}

Для получения полной информации, посетите https://developervillage.blogspot.com/2019/05/send-ftl-in-email-using-spring-boot-in.html