从android以编程方式发送电子邮件

时间:2016-01-28 13:52:57

标签: java android email

我正在尝试从Android手机以编程方式发送电子邮件。我指的是这篇文章How To Send Email Without User Interaction Using SMTP

我按照步骤完成了它。问题是应用程序没有运行。如果有错误,请参考我的代码或建议我解决此问题的解决方案。感谢。

Mail.java代码



package com.example.sendemailfromandroid;


import java.util.Date; 
import java.util.Properties; 
import javax.activation.CommandMap; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.activation.MailcapCommandMap; 
import javax.mail.BodyPart; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 


public class Mail extends javax.mail.Authenticator { 
	private String _user; 
	private String _pass; 

	private String[] _to; 
	private String _from; 

	private String _port; 
	private String _sport; 

	private String _host; 

	private String _subject; 
	private String _body; 

	private boolean _auth; 

	private boolean _debuggable; 

	private Multipart _multipart; 


	public Mail() { 
		_host = "smtp.gmail.com"; // default smtp server 
		_port = "465"; // default smtp port 
		_sport = "465"; // default socketfactory port 

		_user = ""; // username 
		_pass = ""; // password 
		_from = ""; // email sent from 
		_subject = ""; // email subject 
		_body = ""; // email body 

		_debuggable = false; // debug mode on or off - default off 
		_auth = true; // smtp authentication - default on 

		_multipart = new MimeMultipart(); 

		// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
		MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
		mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
		mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
		mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
		mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
		mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
		CommandMap.setDefaultCommandMap(mc); 
	}
	

	public Mail(String user, String pass) { 
		this(); 

		_user = user; 
		_pass = pass; 
	} 

	public boolean send() throws Exception { 
		Properties props = _setProperties(); 

		if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { 
			Session session = Session.getInstance(props, this); 

			MimeMessage msg = new MimeMessage(session); 

			msg.setFrom(new InternetAddress(_from)); 

			InternetAddress[] addressTo = new InternetAddress[_to.length]; 
			for (int i = 0; i < _to.length; i++) { 
				addressTo[i] = new InternetAddress(_to[i]); 
			} 
			msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

			msg.setSubject(_subject); 
			msg.setSentDate(new Date()); 

			// setup message body 
			BodyPart messageBodyPart = new MimeBodyPart(); 
			messageBodyPart.setText(_body); 
			_multipart.addBodyPart(messageBodyPart); 

			// Put parts in message 
			msg.setContent(_multipart); 

			// send email 
			Transport.send(msg); 

			return true; 
		} else { 
			return false; 
		} 
	} 

	public void addAttachment(String filename) throws Exception { 
		BodyPart messageBodyPart = new MimeBodyPart(); 
		DataSource source = new FileDataSource(filename); 
		messageBodyPart.setDataHandler(new DataHandler(source)); 
		messageBodyPart.setFileName(filename); 

		_multipart.addBodyPart(messageBodyPart); 
	} 

	@Override 
	public PasswordAuthentication getPasswordAuthentication() { 
		return new PasswordAuthentication(_user, _pass); 
	} 

	private Properties _setProperties() { 
		Properties props = new Properties(); 

		props.put("mail.smtp.host", _host); 

		if(_debuggable) { 
			props.put("mail.debug", "true"); 
		} 

		if(_auth) { 
			props.put("mail.smtp.auth", "true"); 
		} 

		props.put("mail.smtp.port", _port); 
		props.put("mail.smtp.socketFactory.port", _sport); 
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
		props.put("mail.smtp.socketFactory.fallback", "false"); 

		return props; 
	} 

	// the getters and setters 
	public String getBody() { 
		return _body; 
	} 

	public void setBody(String _body) { 
		this._body = _body; 
	} 

	public void setTo(String[] toArr) {
		this._to = toArr;
	}

	public void setFrom(String string) {
		this._from = string;
	}

	public void setSubject(String string) {
		this._subject = string;
	}

	// more of the getters and setters ….. 
}  
&#13;
&#13;
&#13;

主要活动代码:

&#13;
&#13;
package com.example.sendemailfromandroid;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
 
public class MainActivity extends Activity {
	private Mail m;
	/** Called when the activity is first created. */
	@Override 
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.activity_main); 
		m = new Mail("xxxxxxx@gmail.com", "xxxxxxxxx"); 
	}
 
	public void sendEmail(View view){
		String[] toArr = {"zzzzzzzz@gmail.com"}; // This is an array, you can add more emails, just separate them with a coma
		m.setTo(toArr); // load array to setTo function
		m.setFrom("xxxxxxx@gmail.com"); // who is sending the email 
		m.setSubject("subject"); 
		m.setBody("your message goes here"); 
 
		try { 
			//m.addAttachment("/sdcard/myPicture.jpg");  // path to file you want to attach
			if(m.send()) { 
				// success
				Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
			} else { 
				// failure
				Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
			} 
		} catch(Exception e) { 
			// some other problem
			Toast.makeText(MainActivity.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
		} 
 
	}
}
&#13;
&#13;
&#13;

activity_main.xml中:

&#13;
&#13;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sendemailfromandroid.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Send Mail"
        android:onClick="sendEmail" />

</RelativeLayout>
&#13;
&#13;
&#13;

logotcat:

&#13;
&#13;
01-28 17:33:11.821: W/ResourcesManager(15519): getTopLevelResources: com.example.sendemailfromandroid for user  0
01-28 17:33:11.821: I/InjectionManager(15519): Inside getClassLibPath + mLibMap{0=, 1=}
01-28 17:33:11.831: I/InjectionManager(15519): Inside getClassLibPath caller 
01-28 17:33:11.831: D/InjectionManager(15519): InjectionManager
01-28 17:33:11.831: D/InjectionManager(15519): fillFeatureStoreMap com.example.sendemailfromandroid
01-28 17:33:11.831: I/InjectionManager(15519): Constructor com.example.sendemailfromandroid, Feature store :{}
01-28 17:33:11.831: I/InjectionManager(15519): featureStore :{}
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.841: W/ResourcesManager(15519): getTopLevelResources: com.example.sendemailfromandroid for user  0
01-28 17:33:11.841: W/ResourcesManager(15519): getTopLevelResources: com.example.sendemailfromandroid for user  0
01-28 17:33:11.841: D/DisplayManager(15519): DisplayManager()
01-28 17:33:11.881: D/PhoneWindow(15519): *FMB* installDecor mIsFloating : false
01-28 17:33:11.881: D/PhoneWindow(15519): *FMB* installDecor flags : 8454400
01-28 17:33:11.891: I/art(15519): Rejecting re-init on previously-failed class java.lang.Class<com.example.sendemailfromandroid.Mail>
01-28 17:33:11.891: D/AndroidRuntime(15519): Shutting down VM
01-28 17:33:11.891: E/AndroidRuntime(15519): FATAL EXCEPTION: main
01-28 17:33:11.891: E/AndroidRuntime(15519): Process: com.example.sendemailfromandroid, PID: 15519
01-28 17:33:11.891: E/AndroidRuntime(15519): java.lang.NoClassDefFoundError: com.example.sendemailfromandroid.Mail
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at com.example.sendemailfromandroid.MainActivity.onCreate(MainActivity.java:15)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.Activity.performCreate(Activity.java:6178)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.ActivityThread.access$900(ActivityThread.java:177)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.os.Handler.dispatchMessage(Handler.java:102)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.os.Looper.loop(Looper.java:135)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at android.app.ActivityThread.main(ActivityThread.java:5910)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at java.lang.reflect.Method.invoke(Native Method)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at java.lang.reflect.Method.invoke(Method.java:372)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
01-28 17:33:11.891: E/AndroidRuntime(15519): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
01-28 17:33:13.241: I/Process(15519): Sending signal. PID: 15519 SIG: 9
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
            "mailto","abc@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivity(Intent.createChooser(emailIntent, "Send email..."));

发送到1个以上的地址

intent.putExtra(Intent.EXTRA_EMAIL, addresses); // String[] addresses

答案 1 :(得分:0)

如果您查看错误:java.lang.NoClassDefFoundError: com.example.sendemailfromandroid.Mail它说它无法找到,并且在那里,您无法在{Mail课程中使用onCreate()课程1}}。

来自Java上的NoClassDefFoundError文档:

  

如果Java虚拟机或ClassLoader实例尝试加载类的定义(作为普通方法调用的一部分或作为使用新表达式创建新实例的一部分),则抛出该类,并且没有类的定义可以被发现。   当编译当前正在执行的类时,搜索的类定义存在,但无法再找到定义。

我会检查您的包结构,以确保您的导入正确。如果您的文件位于同一文件夹中并且仍然遇到此问题,请尝试单独编译Mail类,看看是否有任何错误。