java_mail 发送邮件

1.资源

1.1使用JavaMail这个JAR包

下载地址:

http://download.csdn.net/detail/zmnqazqaz/9399175

java_mail 发送邮件_第1张图片

1.2.准备一个用来发送邮件的邮箱



2.代码


2.1 把邮件服务器和发邮件的邮箱做成配置文件

#smtp服务器
mail.smtp.host=smtp.sina.com
#身份验证
mail.smtp.auth=true
#--------------------------------------------------------------

#发送者邮箱
[email protected]


#发送者密码
mail.sender.password=1111


2.2 代码

package com.ist.shjlog;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
import javax.mail.internet.MimeUtility;

import android.content.Context;

public class JavaMailWithAttachment {
    private MimeMessage message;
    private Session session;
    private Transport transport;

    private String mailHost = "";
    private String sender_username = "";
    private String sender_password = "";

    private Properties properties = new Properties();
    
    private Context context=null;

    /*
     * 初始化方法
     */
    public JavaMailWithAttachment(boolean debug,Context context) {
  //  public JavaMailWithAttachment(boolean debug,Context context) {//java
    	this.context =context;
   
        Properties pro = new Properties();
      	
        try {
       //   InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");//java
        	InputStream in = context.getAssets().open("MailServer.properties"); 
            properties.load(in);
            this.mailHost = properties.getProperty("mail.smtp.host");
            this.sender_username = properties.getProperty("mail.sender.username");
            this.sender_password = properties.getProperty("mail.sender.password");
        } catch (IOException e) {
            e.printStackTrace();
        }

        session = Session.getInstance(properties);
        session.setDebug(debug);// 开启后有调试信息
        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     * 
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUser
     *            收件人地址
     * @param attachment
     *            附件
     */
    public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser[], File attachment) {
        try {
            // 发件人
            InternetAddress from = new InternetAddress(sender_username);
            message.setFrom(from);

            // 收件人
            /*
            InternetAddress to = new InternetAddress(receiveUser);
            message.setRecipient(Message.RecipientType.TO, to);
            */
            
            int receiverLen = receiveUser.length;
            for (int i = 0; i < receiverLen; i++) {
                InternetAddress toAddr = new InternetAddress(receiveUser[i]);
                message.addRecipient(javax.mail.Message.RecipientType.TO,toAddr);
             }
            


            // 邮件主题
            message.setSubject(subject);

            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            
            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            
            // 添加附件的内容
            if (attachment != null) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachment);
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                
                // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
                // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
                
                //MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                multipart.addBodyPart(attachmentBodyPart);
            }
            
            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();

            transport = session.getTransport("smtp");
            // smtp验证,就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, sender_username, sender_password);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());

            System.out.println("send success!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    public static void main(String[] args) {
        JavaMailWithAttachment se = new JavaMailWithAttachment(true);
        String to[]={
        		"[email protected]",
        		"[email protected]",
        };
        File affix = new File("c:\\测试-test.txt");
        se.doSendHtmlEmail("邮件主题", "邮件内容", to, affix);//
    }
    */
}


这里注释掉的代码在java运行,在android上配置文件assert目录下

public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser[], File attachment) 

subject 是邮件的主题 

sendHTML是邮件的内容

recevieUser[] 是收件人数组

attachment是附件的路径,如果没有附件使用null



这里注意下:

1.邮件的stmp邮件服务器的地址

2.邮箱需要开通stmp服务才能正常收到邮件 在新浪申请的账号是默认没有开通stmp

3.android下网络的操作必须放到单独的线程才能正常运行



你可能感兴趣的:(java_mail 发送邮件)