首先,我们原本可以直接通过Intent来调用系统邮件客户端发送邮件,但是这种发送需要跳转activity很不方便,所以我打算自己通过smtp协议发送邮件。很幸运,在google code上有一个现成的javaMail的java邮件客户端,我们只需要调用其中的接口就可以了。下面放出使用javaMail的一个demo源代码。
1.自己封装一个邮件发送类MailSender。
public class MailSender extends Authenticator { private String user; private String password; private Session session; private String mailhost = "smtp.gmail.com";//默认用gmail发送 private Multipart messageMultipart; private Properties properties; static { Security.addProvider(new JSSEProvider()); } public MailSender(String user, String password) { this.user = user; this.password = password; properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", mailhost); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.quitwait", "false"); session = Session.getDefaultInstance(properties, this); messageMultipart=new MimeMultipart(); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } public synchronized void sendMail(String subject, String body, String sender, String recipients,String attachment) throws Exception { MimeMessage message = new MimeMessage(session); message.setSender(new InternetAddress(sender));//邮件发件人 message.setSubject(subject);//邮件主题 //设置邮件内容 BodyPart bodyPart=new MimeBodyPart(); bodyPart.setText(body); messageMultipart.addBodyPart(bodyPart); // message.setDataHandler(handler); //设置邮件附件 if(attachment!=null){ DataSource dataSource=new FileDataSource(attachment); DataHandler dataHandler=new DataHandler(dataSource); bodyPart.setDataHandler(dataHandler); bodyPart.setFileName(attachment.substring(attachment.lastIndexOf("/")+1)); } message.setContent(messageMultipart); if (recipients.indexOf(',') > 0) //多个联系人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else //单个联系人 message.setRecipient(Message.RecipientType.TO, new InternetAddress( recipients)); Transport.send(message); } //继承DataSource设置字符编码 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 PrintWriter getLogWriter() throws SQLException { // TODO Auto-generated method stub return null; } public int getLoginTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } public void setLogWriter(PrintWriter out) throws SQLException { // TODO Auto-generated method stub } public void setLoginTimeout(int seconds) throws SQLException { // TODO Auto-generated method stub } public boolean isWrapperFor(Class<?> arg0) throws SQLException { // TODO Auto-generated method stub return false; } public <T> T unwrap(Class<T> arg0) throws SQLException { // TODO Auto-generated method stub return null; } public Connection getConnection() throws SQLException { // TODO Auto-generated method stub return null; } public Connection getConnection(String theUsername, String thePassword) throws SQLException { // TODO Auto-generated method stub return null; } } public String getMailhost() { return mailhost; } public void setMailhost(String mailhost) { this.mailhost = mailhost; properties.setProperty("mail.host", this.mailhost); } }
2.JSSE将帮助处理TLS和SSL业务
public class JSSEProvider extends Provider { public JSSEProvider() { super("HarmonyJSSE", 1.0, "Harmony JSSE Provider"); AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() { public Void run() { put("SSLContext.TLS", "org.apache.harmony.xnet.provider.jsse.SSLContextImpl"); put("Alg.Alias.SSLContext.TLSv1", "TLS"); put("KeyManagerFactory.X509", "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl"); put("TrustManagerFactory.X509", "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl"); return null; } }); } }
3.主activity调用邮件发送类
public class MainActivity extends Activity { private Button sendButton = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendButton = (Button) this.findViewById(R.id.send_btn); sendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub SenderRunnable senderRunnable = new SenderRunnable( "xxxxxxx@163.com", "xxxxxxxx"); senderRunnable.setMail("this is the test subject", "this is the test body", "xxxxxxxxx@gmail.com","/mnt/sdcard/test.txt"); new Thread(senderRunnable).start(); } }); } public boolean onCreateOptionsMenu(Menu menu) { } //android3.2不允许主线程通信 class SenderRunnable implements Runnable { private String user; private String password; private String subject; private String body; private String receiver; private MailSender sender; private String attachment; public SenderRunnable(String user, String password) { this.user = user; this.password = password; sender = new MailSender(user, password); String mailhost=user.substring(user.lastIndexOf("@")+1, user.lastIndexOf(".")); if(!mailhost.equals("gmail")){ mailhost="smtp."+mailhost+".com"; Log.i("hello", mailhost); sender.setMailhost(mailhost); } } public void setMail(String subject, String body, String receiver,String attachment) { this.subject = subject; this.body = body; this.receiver = receiver; this.attachment=attachment; } public void run() { // TODO Auto-generated method stub try { sender.sendMail(subject, body, user, receiver,attachment); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
项目全部源码下载地址:http://download.csdn.net/detail/xanxus46/4888658
javaMail地址:http://code.google.com/p/javamail-android/,使用时记得把三个jar包导入构建路径