我将 Java 电子邮件 API 用于电子邮件功能。它似乎不起作用,因为没有发送电子邮件。我的代码中没有任何异常(因此它似乎正确连接到 smtp),并且当我调试它时,它似乎运行良好。所以我想知道我的代码是否还有其他问题?在这里,还有相关的进口。类中还有一个“createBody()”方法,但它只用信息填充消息,所以我认为这并不重要。
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
public Mail() {
}
static public boolean sendHtml(Commission commission, String mailServer, InternetAddress fromAddress, InternetAddress ccAddress, String subject, String header) throws Exception {
try {
String body = createBody(commission);
InternetAddress toAddress = new InternetAddress(commission.getForm().getActiveReceiver().getEmail());
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
Session session = Session.getDefaultInstance(props);
//Instantiate a message holder
Message msg = new MimeMessage(session);
msg.setHeader("Content-Type", "text/plain; charset='iso-8859-1'");
//From
msg.setFrom(fromAddress);
//To
msg.addRecipient(Message.RecipientType.TO, toAddress);
//CC
if (ccAddress != null)
msg.addRecipient(Message.RecipientType.CC, ccAddress);
//Subject
if (!subject.equals(""))
msg.setSubject(subject);
//Date
msg.setSentDate(new Date());
//Begin
StringBuffer sb = new StringBuffer();
sb.append("<html>\n");
sb.append("<head>\n");
sb.append("<title>\n");
sb.append("</title>\n");
sb.append("<style type=\"text/css\">\n");
sb.append("*{font-family: Tahoma; font-size: 11px; font-weight: normal; color: #51514F;}\n");
sb.append("body{background-color: #FEF8EA;}\n");
sb.append("tr.odd {background-color: #F3F3F3;border: 1px #F3F3F3 solid;}\n");
sb.append("tr.even {background-color: #FFFFFF;border: 1px #FFFFFF solid;}\n");
sb.append("th {font-weight: bold; background-color:#F3F3F3; border-bottom: 1px solid #E2D6BC;}\n");
sb.append("p.header {font-weight: bold;}\n");
sb.append("table {border-collapse:collapse; border: 1px solid #E2D6BC;}\n");
sb.append("td.center {text-align:center;}\n");
sb.append("</style>\n");
sb.append("</head>\n");
sb.append("<body>\n");
//Header
if (!header.equals(""))
sb.append("<h1>"+header+"</h1>");
//Body
if (!body.equals(""))
sb.append(body);
//End
sb.append("</body>\n");
sb.append("</htmnl>\n");
msg.setContent(sb.toString(), "text/html");
System.out.println("About to connect");
//Connect
Transport transport = session.getTransport("smtp");
transport.connect();
//Sending the mail
transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
//Sending the CC mail
if (ccAddress != null)
transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.CC));
//Close
transport.close();
} catch (Exception e) {
throw e;
}
return true;
}
}