我正在尝试在应用程序中发送邮件。我不会弹出与用户的任何交互。我有两个java代码。
MainActivity.java
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
public static String EXTRA_MESSAGE = "com.example.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void sendMessage(View view)
{
try {
test sender = new test();
sender.send();
Toast.makeText(getApplicationContext(), "Message Sent!!! :)", Toast.LENGTH_LONG).show();
} catch (Exception e) {
//Log.e("SendMail", e.getMessage(), e);
}
}
public void exit(View view)
{
System.exit(0);
}
}
test.java
package com.example.test;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import android.widget.Toast;
public class test extends MainActivity
{
public void send()
{
String host = "smtp.gmail.com";
String from = "MYUSERNAME";
String pass = "MYPASS";
try
{
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
String[] to = {"ADDRESSTOSEND@gmail.com"}; // added this line
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i=0; i < to.length; i++ ) { // changed from a while loop
toAddress[i] = new InternetAddress(to[i]);
}
System.out.println(Message.RecipientType.TO);
for( int i=0; i < toAddress.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject("This is subject");
message.setText("Welcome to your mail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error" + e, Toast.LENGTH_LONG).show();
}
}
}
当我按下发送按钮时,我无法发送邮件。我已经使用 xml onClick 调用了 sendMessage()。
eclipse中没有错误。该项目编译,安装,但我没有收到邮件。当我尝试只使用 javajavac
并运行 test.java 时,它工作正常。我在我的帐户中收到邮件。
谢谢你帮助我。