我在向我的應用程序發送電子郵件到Gmail電子郵件ID時遇到一些問題。無法使用JavaMail API將電子郵件發送到Gmail
我使用JavaMail Api
發送電子郵件。
當我按下「發送」按鈕時,會顯示Toast消息「發送成功」,方法爲onPostExecute
,但沒有新的電子郵件發送到我在程序中使用的Gmail ID。
我需要幫助!
我下面的代碼:
public class GmailSender extends Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new android.readnews.support.JSSEProvider());
}
public GmailSender(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 synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
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);
if (recipients.indexOf(',') > 0) {
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
} else {
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipients));
}
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
而且
public class SendEmailFragment extends Fragment implements OnClickListener {
Context mContext = null;
Session session = null;
ProgressDialog pDialog = null;
EditText edtYourEmail, edtSubjectEmail, edtBodyEmail;
final String myEmail = "[email protected]";
final String myPass = "abcxyz";
String yourEmail = "";
String Subject = "";
String BodyEmail = "";
GmailSender sender;
public SendEmailFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sendemail_layout, container,
false);
mContext = container.getContext();
ImageButton btnSendMail = (ImageButton) rootView
.findViewById(R.id.buttonSend);
edtYourEmail = (EditText) rootView.findViewById(R.id.tv_MailFromBox);
edtSubjectEmail = (EditText) rootView
.findViewById(R.id.editTextSubject);
edtBodyEmail = (EditText) rootView.findViewById(R.id.editMessage);
btnSendMail.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
yourEmail = edtYourEmail.getText().toString().trim();
Subject = edtSubjectEmail.getText().toString().trim();
BodyEmail = edtBodyEmail.getText().toString();
pDialog = ProgressDialog.show(mContext, "", "Sending Mail...", true);
SendMail sendmailTask = new SendMail();
sendmailTask.execute();
}
class SendMail extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... arg0) {
try {
sender = new GmailSender(myEmail, myPass);
sender.sendMail(Subject, BodyEmail, myEmail, yourEmail);
return true;
} catch (Exception e) {
Log.i("abc ", "abc " + e.getMessage());
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (result == true) {
pDialog.dismiss();
edtYourEmail.setText("");
edtSubjectEmail.setText("");
edtBodyEmail.setText("");
Toast.makeText(mContext, "Sending success", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(mContext, "Sending failure", Toast.LENGTH_SHORT)
.show();
}
super.onPostExecute(result);
}
}
}
logcat的
01-13 15:35:15.697: W/System.err(1394): javax.mail.AuthenticationFailedException
01-13 15:35:15.697: W/System.err(1394): at javax.mail.Service.connect(Service.java:319)
01-13 15:35:15.697: W/System.err(1394): at javax.mail.Service.connect(Service.java:169)
01-13 15:35:15.697: W/System.err(1394): at javax.mail.Service.connect(Service.java:118)
01-13 15:35:15.697: W/System.err(1394): at javax.mail.Transport.send0(Transport.java:188)
01-13 15:35:15.697: W/System.err(1394): at javax.mail.Transport.send(Transport.java:118)
01-13 15:35:15.697: W/System.err(1394): at android.readnews.support.GmailSender.sendMail(GmailSender.java:67)
01-13 15:35:15.697: W/System.err(1394): at android.readnews.main.SendEmailFragment$SendMail.doInBackground(SendEmailFragment.java:93)
01-13 15:35:15.697: W/System.err(1394): at android.readnews.main.SendEmailFragment$SendMail.doInBackground(SendEmailFragment.java:1)
01-13 15:35:15.697: W/System.err(1394): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-13 15:35:15.697: W/System.err(1394): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-13 15:35:15.697: W/System.err(1394): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-13 15:35:15.697: W/System.err(1394): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-13 15:35:15.697: W/System.err(1394): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-13 15:35:15.697: W/System.err(1394): at java.lang.Thread.run(Thread.java:856)
01-13 15:35:15.733: W/InputMethodManagerService(397): Window already focused, ignoring focus gain of: [email protected] attribute=null, token = [email protected]
01-13 15:40:25.134: W/ThrottleService(397): unable to find stats for iface rmnet0
你是否看到日誌中有任何錯誤?由於您在'doInBackground'方法中捕獲併吞下所有異常,因此獲得「發送成功」消息並不奇怪。或者至少在try塊中返回一個非空結果來查看它是否真的成功。 –
@Zoltán我更新超過 –
要獲得快速解決方案,請打印異常消息(例如'System.out.println(e.getMessage())')以快速找出身份驗證失敗的原因,但我建議您執行錯誤處理建議在這個答案:http://stackoverflow.com/a/7133284/900130 –