DBMNG数据库管理与应用

抓住自己最有兴趣的东西,由浅入深,循序渐进地学……
当前位置:首页 > SQLite > 管理工具

android使用JavaMail

Javamail-Android配置步骤:

  1. 下载Android版本JavaMail包,additional.jar、mail.jar和activation.jar,下载地址JavaMail-Android

  2. 在项目与src同一目录级别下,新建文件夹lib,将下载的3个jar包放入该文件夹

  3. 右键->Properties->Java Build Path->Libraries,选择Add External JARs,找到项目下lib目录的3个jar包


我的代码有三个类: 
第一个类:MailSenderInfo.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
packagecom.util.mail;
/** 
* 发送邮件需要使用的基本信息 
*/ 
importjava.util.Properties; 
publicclassMailSenderInfo { 
    // 发送邮件的服务器的IP和端口 
    privateString mailServerHost; 
    privateString mailServerPort ="25"; 
    // 邮件发送者的地址 
    privateString fromAddress; 
    // 邮件接收者的地址 
    privateString toAddress; 
    // 登陆邮件发送服务器的用户名和密码 
    privateString userName; 
    privateString password; 
    // 是否需要身份验证 
    privatebooleanvalidate =false; 
    // 邮件主题 
    privateString subject; 
    // 邮件的文本内容 
    privateString content; 
    // 邮件附件的文件名 
    privateString[] attachFileNames;   
    /** 
      * 获得邮件会话属性 
      */ 
    publicProperties getProperties(){ 
      Properties p =newProperties(); 
      p.put("mail.smtp.host",this.mailServerHost); 
      p.put("mail.smtp.port",this.mailServerPort); 
      p.put("mail.smtp.auth", validate ?"true":"false"); 
      returnp; 
    } 
    publicString getMailServerHost() { 
      returnmailServerHost; 
    } 
    publicvoidsetMailServerHost(String mailServerHost) { 
      this.mailServerHost = mailServerHost; 
    }
    publicString getMailServerPort() { 
      returnmailServerPort; 
    }
    publicvoidsetMailServerPort(String mailServerPort) { 
      this.mailServerPort = mailServerPort; 
    }
    publicbooleanisValidate() { 
      returnvalidate; 
    }
    publicvoidsetValidate(booleanvalidate) { 
      this.validate = validate; 
    }
    publicString[] getAttachFileNames() { 
      returnattachFileNames; 
    }
    publicvoidsetAttachFileNames(String[] fileNames) { 
      this.attachFileNames = fileNames; 
    }
    publicString getFromAddress() { 
      returnfromAddress; 
    } 
    publicvoidsetFromAddress(String fromAddress) { 
      this.fromAddress = fromAddress; 
    }
    publicString getPassword() { 
      returnpassword; 
    }
    publicvoidsetPassword(String password) { 
      this.password = password; 
    }
    publicString getToAddress() { 
      returntoAddress; 
    } 
    publicvoidsetToAddress(String toAddress) { 
      this.toAddress = toAddress; 
    } 
    publicString getUserName() { 
      returnuserName; 
    }
    publicvoidsetUserName(String userName) { 
      this.userName = userName; 
    }
    publicString getSubject() { 
      returnsubject; 
    }
    publicvoidsetSubject(String subject) { 
      this.subject = subject; 
    }
    publicString getContent() { 
      returncontent; 
    }
    publicvoidsetContent(String textContent) { 
      this.content = textContent; 
    } 
}

第二个类:MultiMailsender.java

View Code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
packagecom.util.mail;
  
importjava.util.Date;
importjava.util.Properties;
  
importjavax.mail.Address;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
  
/**
 * 发送邮件给多个接收者、抄送邮件
 */
publicclassMultiMailsender {
  
      
    /** 
      * 以文本格式发送邮件 
      * @param mailInfo 待发送的邮件的信息 
      */ 
        publicbooleansendTextMail(MultiMailSenderInfo mailInfo) { 
          // 判断是否需要身份认证 
          MyAuthenticator authenticator =null; 
          Properties pro = mailInfo.getProperties();
          if(mailInfo.isValidate()) { 
          // 如果需要身份认证,则创建一个密码验证器 
            authenticator =newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); 
          }
          // 根据邮件会话属性和密码验证器构造一个发送邮件的session 
          Session sendMailSession = Session.getDefaultInstance(pro,authenticator); 
          try{ 
          // 根据session创建一个邮件消息 
          Message mailMessage =newMimeMessage(sendMailSession); 
          // 创建邮件发送者地址 
          Address from =newInternetAddress(mailInfo.getFromAddress()); 
          // 设置邮件消息的发送者 
          mailMessage.setFrom(from); 
          // 创建邮件的接收者地址,并设置到邮件消息中 
          Address[] tos =null; 
          String[] receivers = mailInfo.getReceivers();
          if(receivers !=null){
              // 为每个邮件接收者创建一个地址
              tos =newInternetAddress[receivers.length +1];
              tos[0] =newInternetAddress(mailInfo.getToAddress());
              for(inti=0; i<receivers.length; i++){
                  tos[i+1] =newInternetAddress(receivers[i]);
              }
          }else{
              tos =newInternetAddress[1];
              tos[0] =newInternetAddress(mailInfo.getToAddress());
          }
  
          // Message.RecipientType.TO属性表示接收者的类型为TO 
          mailMessage.setRecipients(Message.RecipientType.TO,tos); 
          // 设置邮件消息的主题 
          mailMessage.setSubject(mailInfo.getSubject()); 
          // 设置邮件消息发送的时间 
          mailMessage.setSentDate(newDate()); 
          // 设置邮件消息的主要内容 
          String mailContent = mailInfo.getContent(); 
          mailMessage.setText(mailContent); 
          // 发送邮件 
          Transport.send(mailMessage);
          returntrue; 
          }catch(MessagingException ex) { 
              ex.printStackTrace(); 
          } 
          returnfalse; 
        } 
    /**
     * 发送邮件给多个接收者,以Html内容
     * @param mailInfo    带发送邮件的信息
     * @return
     */
    publicstaticbooleansendMailtoMultiReceiver(MultiMailSenderInfo mailInfo){
        MyAuthenticator authenticator =null;
        if(mailInfo.isValidate()) {
            authenticator =newMyAuthenticator(mailInfo.getUserName(),
                    mailInfo.getPassword());
        }
        Session sendMailSession = Session.getInstance(mailInfo
                .getProperties(), authenticator);
        try{
            Message mailMessage =newMimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from =newInternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address[] tos =null;
            String[] receivers = mailInfo.getReceivers();
            if(receivers !=null){
                // 为每个邮件接收者创建一个地址
                tos =newInternetAddress[receivers.length +1];
                tos[0] =newInternetAddress(mailInfo.getToAddress());
                for(inti=0; i<receivers.length; i++){
                    tos[i+1] =newInternetAddress(receivers[i]);
                }
            }else{
                tos =newInternetAddress[1];
                tos[0] =newInternetAddress(mailInfo.getToAddress());
            }
            // 将所有接收者地址都添加到邮件接收者属性中
            mailMessage.setRecipients(Message.RecipientType.TO, tos);
              
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(newDate());
            // 设置邮件内容
            Multipart mainPart =newMimeMultipart();
            BodyPart html =newMimeBodyPart();
            html.setContent(mailInfo.getContent(),"text/html; charset=GBK");
            mainPart.addBodyPart(html);
            mailMessage.setContent(mainPart);
            // 发送邮件
            Transport.send(mailMessage);
            returntrue;
        }catch(MessagingException ex) {
            ex.printStackTrace();
        }
        returnfalse;
    }
      
    /**
     * 发送带抄送的邮件
     * @param mailInfo    待发送邮件的消息
     * @return
     */
    publicstaticbooleansendMailtoMultiCC(MultiMailSenderInfo mailInfo){
        MyAuthenticator authenticator =null;
        if(mailInfo.isValidate()) {
            authenticator =newMyAuthenticator(mailInfo.getUserName(),
                    mailInfo.getPassword());
        }
        Session sendMailSession = Session.getInstance(mailInfo
                .getProperties(), authenticator);
        try{
            Message mailMessage =newMimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from =newInternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to =newInternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);
              
            // 获取抄送者信息
            String[] ccs = mailInfo.getCcs();
            if(ccs !=null){
                // 为每个邮件接收者创建一个地址
                Address[] ccAdresses =newInternetAddress[ccs.length];
                for(inti=0; i<ccs.length; i++){
                    ccAdresses[i] =newInternetAddress(ccs[i]);
                }
                // 将抄送者信息设置到邮件信息中,注意类型为Message.RecipientType.CC
                mailMessage.setRecipients(Message.RecipientType.CC, ccAdresses);
            } 
              
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(newDate());
            // 设置邮件内容
            Multipart mainPart =newMimeMultipart();
            BodyPart html =newMimeBodyPart();
            html.setContent(mailInfo.getContent(),"text/html; charset=GBK");
            mainPart.addBodyPart(html);
            mailMessage.setContent(mainPart);
            // 发送邮件
            Transport.send(mailMessage);
            returntrue;
        }catch(MessagingException ex) {
            ex.printStackTrace();
        }
        returnfalse;
    }
      
    /**
     * 发送多接收者类型邮件的基本信息
     */
    publicstaticclassMultiMailSenderInfoextendsMailSenderInfo{
        // 邮件的接收者,可以有多个
        privateString[] receivers;
        // 邮件的抄送者,可以有多个
        privateString[] ccs;
          
        publicString[] getCcs() {
            returnccs;
        }
        publicvoidsetCcs(String[] ccs) {
            this.ccs = ccs;
        }
        publicString[] getReceivers() {
            returnreceivers;
        }
        publicvoidsetReceivers(String[] receivers) {
            this.receivers = receivers;
        }
    }
}

第三个类:MyAuthenticator.java

View Code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
packagecom.util.mail;
   
importjavax.mail.*;
     
publicclassMyAuthenticatorextendsAuthenticator{
    String userName=null;
    String password=null;
        
    publicMyAuthenticator(){
    }
    publicMyAuthenticator(String username, String password) { 
        this.userName = username; 
        this.password = password; 
    } 
    protectedPasswordAuthentication getPasswordAuthentication(){
        returnnewPasswordAuthentication(userName, password);
    }
}

下面给出使用上面三个类的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
publicstaticvoidmain(String[] args){
         //这个类主要是设置邮件
      MultiMailSenderInfo mailInfo =newMultiMailSenderInfo(); 
      mailInfo.setMailServerHost("smtp.163.com"); 
      mailInfo.setMailServerPort("25"); 
      mailInfo.setValidate(true); 
      mailInfo.setUserName("xxx@163.com"); 
      mailInfo.setPassword("**********");//您的邮箱密码 
      mailInfo.setFromAddress("xxx@163.com"); 
      mailInfo.setToAddress("xxx@163.com"); 
      mailInfo.setSubject("设置邮箱标题"); 
      mailInfo.setContent("设置邮箱内容");
      String[] receivers =newString[]{"***@163.com","***@tom.com"}; 
      String[] ccs = receivers; mailInfo.setReceivers(receivers); 
      mailInfo.setCcs(ccs); 
      //这个类主要来发送邮件 
      MultiMailsender sms =newMultiMailsender(); 
      sms.sendTextMail(mailInfo);//发送文体格式 
      MultiMailsender.sendHtmlMail(mailInfo);//发送html格式 
      MultiMailsender.sendMailtoMultiCC(mailInfo);//发送抄送

最后,给出朋友们几个注意的地方: 
1、使用此代码你可以完成你的javamail的邮件发送功能、发多个邮箱。三个类缺一不可。 
2、这三个类我打包是用的com.util.mail包,如果不喜欢,你可以自己改,但三个类文件必须在同一个包中 
3、不要使用你刚刚注册过的邮箱在程序中发邮件,如果你的163邮箱是刚注册不久,那你就不要使用“smtp.163.com”。因为你发不出去。刚注册的邮箱是不会给你这种权限的,也就是你不能通过验证。要使用你经常用的邮箱,而且时间比较长的。 
4、另一个问题就是mailInfo.setMailServerHost("smtp.163.com");与mailInfo.setFromAddress("xxx@163.com");这两句话。即如果你使用163smtp服务器,那么发送邮件地址就必须用163的邮箱,如果不的话,是不会发送成功的。 
5、关于javamail验证错误的问题,网上的解释有很多,但我看见的只有一个。就是我的第三个类。你只要复制全了代码,我想是不会有问题的。

6、 然后在Android项目中添加网络访问权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号