gpt4 book ai didi

java - 通过javamail在邮件中嵌入图像时出错

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:42 25 4
gpt4 key购买 nike

这是我使用 javax.mail.1.5.2 向用户发送邮件的代码。我需要附上一些图片。我为此使用了servetcontext getRealPath。但它说 ServletContextEvent 变量 sce (参见代码)需要初始化。有一些东西缺失了。这是我的代码。

public void sendSSLMessage(String recipients[], String subject,
String htmlText, String from , MailSSLSocketFactory sf) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication

getPasswordAuthentication() {
return new
PasswordAuthentication("support@jiffie.in", "support@1234$");
}
});

session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
/*Message msg = new MimeMessage(session);*/
InternetAddress addressFrom = new InternetAddress(from);
message.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
MimeMultipart multipart = new MimeMultipart("related");

// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html");

// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
ServletContextEvent sce;
ServletContext context = sce.getServletContext(); //this shows error. sce may not have been initialized
String contextPath = context.getRealPath("/");
//...
File contextDir = new File(contextPath);
File emailImage = new File(contextDir, "img/logo.png");
DataSource fds = new FileDataSource(emailImage );
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<logo>");
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);

// Setting the Subject and Content Type
message.setSubject(subject);

Transport.send(message);
}

最佳答案

首先,通过修复所有这些 common JavaMail mistakes 来清理您的代码.

sce 只是出现在程序的中间,而没有被分配值,这就是它提示未初始化的原因。但实际上,如果您只需要 ServletContext,请摆脱 sce 并使用 javax.servlet.ServletRequest 方法 getServletContext()。但是您需要从调用此方法的 Servlet 中传入“请求”对象。

关于java - 通过javamail在邮件中嵌入图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com