我是编程新手。我不明白什么是错的。此代码始终返回FALSE,但会发送该字母。注意“结果”变量。可能是我没有正确描述它。提前谢谢!
public class Send extends javax.mail.Authenticator
{
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
protected boolean result;
public String sss = "";
public static final String LOG_TAG = "LOG";
public Send(String user, String password)
{
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}
public boolean sendMail (final String subject,
final String body,
final String sender,
final String recipients,
final String FileName)
{
Thread SendThread = new Thread()
{
public void run()
{
try
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(FileName)
{
@Override
public String getContentType()
{
return "application/octet-stream";
}
};
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
String Fname = new File (FileName).getName();
attachmentPart.setFileName(Fname);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
result = true;
Log.d(LOG_TAG, "SENDED");
}
catch(Exception e)
{
result = false;
Log.d(LOG_TAG, "FAILED");
}
}
};
SendThread.start();
return result;
}
......
答案 0 :(得分:4)
SendThread.start();
return result;
您(可能)在线程完成之前返回result
的值。如果你需要send是异步的,你不能立即返回它的结果 - 它还没有。如果您需要在发送完成时通知某人/某事,您需要在该主题中为该代码进行编码。