【发布时间】:2018-03-21 14:21:51
【问题描述】:
在 Android Studio 中运行以下代码后,我遇到了问题:-
java.lang.RuntimeException: javax.mail.MessagingException: 不能 连接到 SMTP 主机:localhost,端口:25;嵌套异常是: java.net.SocketException:权限被拒绝
它使用的是 localhost 和 25 端口,而不是分配的主机和端口。
public class GMailSender extends Authenticator {
private String user;
private String password;
private Session session;
public GMailSender(final String user, final String password) {
this.user = user;
this.password = password;
//Properties props = new Properties();
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("garimabareja28@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("garimabareja28@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
请帮帮我。
提前致谢!
【问题讨论】:
-
After running following code in Android Studio,那是不可能的。它只能在您的 Android 设备上运行。或者安卓模拟器。那么你正在做什么?请编辑您的帖子以提供此信息。 -
我没有做太多的 Android 开发,但看起来你在构造函数中重新定义了
session属性,而不是简单地实例化它。你可能想调查一下。
标签: android