基本上,我正在尝试使用带有以下代码的mailgun发送电子邮件,它可以正常编译,但是在运行.class文件时出现以下错误:
错误:无法初始化主类EmailClient 原因:java.lang.NoClassDefFoundError:javax / mail / Message
我在同一目录中下载了activation.jar,javax.mail.jar,mail.jar文件,并将编译参数设置为javac EmailClient.java -cp .:activation.jar:javax.mail.jar:mail.jar
和java EmailClient -cp .:activation.jar:javax.mail.jar:mail.jar
,但仍然出现错误。 / p>
我的代码:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailClient {
private static final String senderEmail = "test@logicbig.com";//change with your sender email
private static final String senderPassword = "12345678";//change with your sender password
public static void sendAsHtml(String to, String title, String html) throws MessagingException {
System.out.println("Sending email to " + to);
Session session = createSession();
//create message using session
MimeMessage message = new MimeMessage(session);
prepareEmailMessage(message, to, title, html);
//sending message
Transport.send(message);
System.out.println("Done");
}
private static void prepareEmailMessage(MimeMessage message, String to, String title, String html)
throws MessagingException {
message.setContent(html, "text/html; charset=utf-8");
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(title);
}
private static Session createSession() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");//Outgoing server requires authentication
props.put("mail.smtp.starttls.enable", "true");//TLS must be activated
props.put("mail.smtp.host", "smtp.1and1.com"); //Outgoing server (SMTP) - change it to your SMTP server
props.put("mail.smtp.port", "587");//Outgoing port
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, senderPassword);
}
});
return session;
}
public static void main(String[] args) throws MessagingException {
EmailClient.sendAsHtml("testreceiver10@gmail.com",
"Test email",
"<h2>Java Mail Example</h2><p>hi there!</p>");
}
}