我已经进行了一段时间的故障排除,可能会受到XY problem的影响,因此这将是相当具有描述性的。
目标:点击按钮发送简单的电子邮件,而不利用外部邮件应用。
研究导致了JavaMail API,它在个人计算机上成功编译,测试和执行。
因此,在花了一些时间阅读答案后,我按照这些步骤添加了库。
除此之外,我还做了以下几点:
gradlew clean
以及gradlew build
已尝试过其他一些失败的方法,但这些是最新的一系列步骤。 Android Studio会检测文件,但在执行时,应用程序会崩溃NoClassDefFoundError
。 Intuition说这个问题是类路径,但在尝试了几种不同但无效的解决方案后,现在可以提供更有经验的建议。
供参考:
MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button testButton = (Button) findViewById(R.id.emailButton);
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Emailer.send(getApplicationContext());
}
});
}
}
的emailer:
import android.content.Context;
import android.widget.Toast;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Emailer {
public static void send(Context context) {
// Recipient's email
String recipient = "myemail@gmail.com";
// Sender information
String sender = "myemail@gmail.com";
final String username = "myUsername";
final String password = "myPassword";
String host = "smtp.gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "25");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// constructing the email
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject("Email Test");
message.setText("Testing the email capability using JavaMailAPI on Android");
// Sending
Transport.send(message);
Toast.makeText(context, R.string.email_success, Toast.LENGTH_SHORT).show();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}