Android邮件发送实现

这里邮件的实现方式使用的是 JavaMail for Andorid,用到的包主要有android-mail和android-activation,具体详情可以参考:https://javaee.github.io/javamail/#JavaMail_for_Android,这里使用的Android studio进行开发,首先是进行配置:

repositories { 
    jcenter()
    maven {
        url "https://maven.java.net/content/groups/public/"
    }
}


android {
    packagingOptions {
        pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
    }
}


dependencies {
    // use whatever the current version is...
    compile 'com.sun.mail:android-mail:1.6.0'
    compile 'com.sun.mail:android-activation:1.6.0'
}

 这里是根据官网进行配置的,但配置完这个后,我的编译结果是会报错的,所以对上面的配置进行了一些修改:

第一点修改:

packagingOptions {
    pickFirst 'META-INF/*' // picks the JavaMail license file
}

第二点修改,在dependencies中添加:

configurations {    all*.exclude group: 'javax.activation', module: 'activation'}

第三点修改,我在3.1.3编译不过,这里我改为3.0.0可以编过:

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }

在这样配置后,编译就没问题了,接下类就是怎么去实现邮件的发送了,这里先来一段官网的小样列,感兴趣的可以自己去看看,地址:https://javaee.github.io/javamail/docs/api/

    Properties props = new Properties();
    props.put("mail.smtp.host", "my-mail-server");
    Session session = Session.getInstance(props, null);

    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom("[email protected]");
        msg.setRecipients(Message.RecipientType.TO,
                          "[email protected]");
        msg.setSubject("JavaMail hello world example");
        msg.setSentDate(new Date());
        msg.setText("Hello, world!\n");
        Transport.send(msg, "[email protected]", "my-password");
    } catch (MessagingException mex) {
        System.out.println("send failed, exception: " + mex);
    }

这就是官网的一个小demo,对于刚开始接触的人,里面的这些配置可能会让你不明所以,会有各种坑在等你,下面将对这些参数进行说明:

1、首先就是: props.put("mail.smtp.host", "my-mail-server");一开始我看到这的时候,这什么东西,完全看不懂,其实这里就是要你配置你是从哪个邮箱发出去的,put方法中的键是你不需要变的,这里举两例,如果你是已QQ发出去,那么这里"my-mail-server"就得改为:smtp.163.com,如果是是163邮箱,那么就是:smtp.163.com,最终代码就改为:props.put("mail.smtp.host", "my-mail-server");如果你是其他邮箱,那你就百度:xx邮箱的smtp设置;

2、msg.setFrom("[email protected]");这里就是你是从哪个邮箱发出去的;

3、msg.setRecipients(Message.RecipientType.TO, "[email protected]");这里是设置收件人的邮箱;

4、msg.setSubject("JavaMail hello world example");    设置邮件的主题;
                msg.setSentDate(new Date());                                  设置有邮件的日期;
                msg.setText("Hello, world!\n");                                   设置邮件的内容;

5、Transport.send(msg, "[email protected]", "my-password");这里需要注意这个my-password,这里传的并不是你邮箱的密码,而是你邮箱的授权码,这里以163邮箱为例:

 这里可以先点掉 :POP3/SMTP服务  后在点上,之后跟着提示走就可以自己设置授权码了。qq邮箱也是需要这样设置得到授权码的,这里就不在说了。

最后这里在贴上我自己修改后的代码:

    private void sendMailMy(){
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");
        Session session = Session.getInstance(props, null);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom("[email protected]");
            msg.setRecipients(Message.RecipientType.TO, "[email protected]");
            msg.setSubject("标题");
            msg.setSentDate(new Date());
            msg.setText("你好!\n这里是来自ubt的信息");
            Transport.send(msg, "[email protected]", "授权码");
        } catch (MessagingException mex) {
            System.out.println("send failed, exception: " + mex);
        }
    }

这里是从我的163邮箱发给了我的qq邮箱,有没有觉得so easy。

但是,这种方式只是发了文本内容,并没有发送附件,而且看起来不舒服,下面就来封装一下,主要分为四个类: 

第一个类是对消息体(Message)的封装,如果你还想设置消息中的其他内容,都可以在这里添加属性,这只是样例:

public class MailSenderInfo {

    private String mailServerHost;
    private String mailServerPort = "25";
    private String fromAddress;
    private String toAddress;
    private String userName;
    private String password;
    private boolean validate = false;
    private String subject;
    private String content;
    private String[] attachFileNames;

    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return mailServerHost;
    }

    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }

    public String getMailServerPort() {
        return mailServerPort;
    }

    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSubject() {
        return subject;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String textContent) {
        this.content = textContent;
    }
}

第二个是对权限的封装,也就是我们发送邮箱的账号和密码(授权码):

public class MailAuthenticator extends Authenticator {

    String userName=null;
    String password=null;

    public MailAuthenticator(){
    }
    public MailAuthenticator(String username, String password) {
        this.userName = username;
        this.password = password;
    }
    // 这个方法在Authenticator内部会调用
    protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName, password);
    }

}

 第三个就是封装一个简易的发送器了,通过这个将邮件发送出去,这里封装了三个方法,第一个是发送纯文本;第二个是发送文本和附件;第三个是以HTML格式发送,可根据需求自行添加:

public class SimpleMailSender {

    /**
     * 以文本格式发送邮件
     *
     * @param mailInfo 待发送的邮件的信息
     */
    public boolean sendTextMail(MailSenderInfo mailInfo) {
        // 判断是否需要身份认证
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份认证,则创建一个密码验证器
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // 设置邮件消息的主要内容
            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);
            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 以文本格式发送邮件并添加附加
     *
     * @param mailInfo 待发送的邮件的信息
     */
    public boolean sendTextAndFileMail(MailSenderInfo mailInfo,String[] filePath) {
        // 判断是否需要身份认证
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份认证,则创建一个密码验证器
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());

            // 添加附件体
            BodyPart messageBodyPart = new MimeBodyPart();
            // 设置邮件消息的主要内容
            messageBodyPart.setContent(mailInfo.getContent(),  "text/html;charset=utf-8");
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            for (int i = 0; i < filePath.length; i++) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                try {
                    //绑定附件路径
                    bodyPart.attachFile(filePath[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                multipart.addBodyPart(bodyPart);
            }
            mailMessage.setContent(multipart);

            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 以HTML格式发送邮件
     *
     * @param mailInfo 待发送的邮件信息
     */
    public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
        // 判断是否需要身份认证
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        //如果需要身份认证,则创建一个密码验证器
        if (mailInfo.isValidate()) {
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            // Message.RecipientType.TO属性表示接收者的类型为TO
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
            Multipart mainPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 设置HTML内容
            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 将MiniMultipart对象设置为邮件内容
            mailMessage.setContent(mainPart);
            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

}

    最后就是将上面三个类需要的信息配置一下就可以发送,这里在抽出一个类:

public class EmailUtil {
    private static final String TAG = "EmailUtil";

    /**
     * @param title  邮件的标题
     * @param msuggestions 邮件的文本内容
     * @param toAddress  收件人的地址  如:[email protected]
     */
    public static void autoSendMail(String title,String msuggestions,String toAddress) {
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.163.com");//smtp地址
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("[email protected]");// 发送方邮件地址
        mailInfo.setPassword("发送邮箱授权码");// 邮箱POP3/SMTP服务授权码
        mailInfo.setFromAddress("[email protected]");// 发送方邮件地址
        mailInfo.setToAddress(toAddress);//接受方邮件地址
        mailInfo.setSubject(title);//设置邮箱标题
        mailInfo.setContent(msuggestions);
        // 这个类主要来发送邮件
        SimpleMailSender sms = new SimpleMailSender();
        sms.sendTextMail(mailInfo);// 发送文体格式
        Log.d(TAG, "autoSendMail: msuggestions: "+msuggestions);
    }

    /**
     * @param title  邮件的标题
     * @param msuggestions 邮件的文本内容
     * @param toAddress  收件人的地址  如:[email protected]
     * @param filePath  附件的路径 
     */
    public static void autoSendFileMail(String title,String msuggestions,String toAddress,String[] filePath) {
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.163.com");//smtp地址
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("[email protected]");// 发送方邮件地址
        mailInfo.setPassword("发送邮箱授权码");// 邮箱POP3/SMTP服务授权码
        mailInfo.setFromAddress("[email protected]");// 发送方邮件地址
        mailInfo.setToAddress(toAddress);//接受方邮件地址
        mailInfo.setSubject(title);//设置邮箱标题
        mailInfo.setContent(msuggestions);
        // 这个类主要来发送邮件
        SimpleMailSender sms = new SimpleMailSender();
        sms.sendTextAndFileMail(mailInfo,filePath);// 发送文体格式
        Log.d(TAG, "autoSendMail: msuggestions: "+msuggestions);
    }
}

这里我是把发送的邮箱定死了,该配的参数也都在这里配好了,其他需要定制的参数传进来就好了,这样就大体完成了,如果有其他需求的可以自行修改,这里提供的只是一个模板。

参考文章:https://www.jianshu.com/p/305baada101b

猜你喜欢

转载自blog.csdn.net/tangedegushi/article/details/81238136