因此,我尝试使用JavaMailSender
、MimeMessage
和MimeMessageHelper
发送一封电子邮件,并在邮件末尾添加一个取消订阅的可单击链接。
package com.emailScheduler.emailScheduler.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
@Service
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private SpringTemplateEngine springTemplateEngine;
//Simple mail sender method
public void sendMail(String to, String sub, String msg){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("Sender Name");
mailMessage.setTo(to);
mailMessage.setSubject(sub);
mailMessage.setText(msg);
javaMailSender.send(mailMessage);
}
//HTML mail sender method
public void sendMail2 (String to, String sub, String msg) throws MessagingException, UnsupportedEncodingException {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
/*Context context = new Context();
context.setVariables(mailModel);*/
String html = "<p>" + msg + "</p>" + "<a href= \"localhost:8080/unsubscribe\">unsubscribe1</a>";
String html2 = "<p>" + msg + "</p>" + "<a href= 'localhost:8080/unsubscribe'>unsubscribe2</a>";
String html3 = html + html2;
messageHelper.setFrom("senderemail@gmail.com", "Sender Name");
messageHelper.setTo(to);
messageHelper.setSubject(sub);
messageHelper.setText(html3, true);
System.out.println(html);
System.out.println(html2);
javaMailSender.send(mailMessage);
}
}
我可以成功发送电子邮件,但在我的邮件正文中,由于某种原因,unsubscribe
没有显示为超链接,而是纯文本,在chrome浏览器的inspect元素中检查时,它显示如下<a>unsubscribe1</a>
2条答案
按热度按时间eqoofvh91#
在超链接URL中使用http或https方案。只有在localhost:8080或localhost:80或任何其他端口的情况下,Gmail才会将HTML电子邮件发送到text。domain.com和其他域也可以在没有方案的情况下工作。
HTML和body标记是可选的。
r3i60tvu2#
尝试仅使用'而不执行转义char =“