在邮件头中放入图像是通过在邮件的HTML内容中嵌入图像的方式实现的。具体步骤如下:
<html>
<body>
<img src="https://example.com/image.jpg" alt="Image">
</body>
</html>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmailWithImage(String recipient, String subject, String htmlContent) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(recipient);
helper.setSubject(subject);
helper.setText(htmlContent, true);
javaMailSender.send(message);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/sendEmail")
public String sendEmail() {
String recipient = "example@example.com";
String subject = "Test Email with Image";
String htmlContent = "<html><body><img src=\"https://example.com/image.jpg\" alt=\"Image\"></body></html>";
try {
emailService.sendEmailWithImage(recipient, subject, htmlContent);
return "Email sent successfully";
} catch (MessagingException e) {
return "Failed to send email";
}
}
}
这样,当访问/sendEmail
接口时,会发送一封包含图像的邮件到指定的收件人邮箱中。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云