我正在尝试使用Java发送电子邮件:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties); …Run Code Online (Sandbox Code Playgroud) 以下是我发送电子邮件的代码:
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", "false");
final Session session = Session.getInstance(props);
final Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setSentDate(new Date());
Multipart multipart = new MimeMultipart("related");
BodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(body, "text/html");
multipart.addBodyPart(mbp1);
Transport.send(msg);
Run Code Online (Sandbox Code Playgroud)
错误堆栈跟踪:
javax.mail.NoSuchProviderException: smtp
at javax.mail.Session.getService(Session.java:764)
at javax.mail.Session.getTransport(Session.java:689)
at javax.mail.Session.getTransport(Session.java:632)
at javax.mail.Session.getTransport(Session.java:612)
at javax.mail.Session.getTransport(Session.java:667)
at javax.mail.Transport.send0(Transport.java:154)
at javax.mail.Transport.send(Transport.java:80)
Run Code Online (Sandbox Code Playgroud)
注意:
- 如果作为桌面应用程序执行,相同的代码.但是在tomcat上部署时抛出异常.
- 最新的mail.jar和smtp.jar被添加到库中.
- SMTP主机地址也是正确的.
如果有人可以指点我会有所帮助.