使用java向邮箱发送邮件


这是我很早之前写的一个工具类,最近在整理自己所学的东西,无意中找到了,就拿出来与大家分享,代码如下:

import java.io.ByteArrayOutputStream;   
import java.io.FileInputStream;   
import java.io.IOException;   
import java.util.Arrays;   
import java.util.Date;   
import java.util.Properties;   
  



import javax.activation.DataHandler;   
import javax.activation.FileDataSource;   
import javax.mail.Authenticator;   
import javax.mail.Message;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeMessage;   
  
import javax.mail.BodyPart;   
import javax.mail.Multipart;   
import javax.mail.internet.MimeBodyPart;   
import javax.mail.internet.MimeMultipart;   

import org.apache.struts.util.MessageResources;

import com.qq.connect.javabeans.tenpay.Address;

//import com.sun.istack.internal.ByteArrayDataSource;  
public class SendMails {
       public  int sendMail(String emailTitle, String content, String emailTo,MessageResources message) throws Exception {
        System.out.println(smtpServer1);
        Properties props = new Properties();   
        props.put("mail.smtp.auth", "true"); 
        props.put( "mail.transport.protocol", "smpt");
        props.put("mail.smtp.host", smtpServer1);
        // 获得邮件会话对象   
        Session session = Session.getInstance(props,new SmtpAuthenticator1(fromMailAddress1, password1));  
        /** *************************************************** */  
        // 创建MIME邮件对象   
        MimeMessage mimeMessage = new MimeMessage(session);   
        mimeMessage.setFrom(new InternetAddress(fromMailAddress1));// 发件人   
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));// 收件人   
        mimeMessage.setSubject(emailTitle);   
        mimeMessage.setSentDate(new Date());// 发送日期   
        Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件   
        /** *************************************************** */  
        BodyPart bodyPart = new MimeBodyPart();// 正文   
       StringBuffer content = new StringBuffer();  
         bodyPart.setDataHandler(new DataHandler(content.toString(),"text/html;charset=GBK"));// 网页格式   
               /** *************************************************** */  
//        BodyPart attachBodyPart = new MimeBodyPart();// 普通附件   
//        FileDataSource fds = new FileDataSource("c:/boot.ini");   
//        attachBodyPart.setDataHandler(new DataHandler(fds));   
//        attachBodyPart.setFileName("=?GBK?B?"+ new sun.misc.BASE64Encoder().encode(fds.getName().getBytes()) + "?=");// 解决附件名中文乱码   
//        mp.addBodyPart(attachBodyPart);   
        /** *************************************************** */  
//        MimeBodyPart imgBodyPart = new MimeBodyPart(); // 附件图标   
//        byte[] bytes = readFile("E:/webcms/webcms/WebContent/images/bjx.jpg");   
//        ByteArrayDataSource fileds = new ByteArrayDataSource(bytes,"application/octet-stream");   
//        imgBodyPart.setDataHandler(new DataHandler(fileds));   
//        imgBodyPart.setFileName("button.gif");   
//        imgBodyPart.setHeader("Content-ID", "<IMG1></IMG1>");// 在html中使用该图片方法src="cid:IMG1"   
//        mp.addBodyPart(imgBodyPart);   
        /** *************************************************** */  
        mp.addBodyPart(bodyPart);
        mimeMessage.setContent(mp);//设置邮件内容对象
        try {
            Transport.send(mimeMessage);//发送邮件
//            Transport transport=session.getTransport();
//            transport.send(mimeMessage);
} catch (Exception e) {
//     e.printStackTrace();
if(e.getMessage().contains("550 User not found")){
return 2;
}else{
return 3;
}
}
        //system.out.println("SendEmail OK!!");
        return 0;
    }  
public void setUsername1(String username1) {
this.username1 = username1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public void setSmtpServer1(String smtpServer1) {
this.smtpServer1 = smtpServer1;
}

public void setFromMailAddress1(String fromMailAddress1) {
this.fromMailAddress1 = fromMailAddress1;
}
 public static byte[] readFile(String file) {   
        FileInputStream fis = null;   
        ByteArrayOutputStream bos = null;   
        try {   
            fis = new FileInputStream(file);   
            bos = new ByteArrayOutputStream();   
            int bytesRead;   
            byte buffer[] = new byte[1024 * 1024];   
            while ((bytesRead = fis.read(buffer)) != -1) {   
                bos.write(buffer, 0, bytesRead);   
                Arrays.fill(buffer, (byte) 0);   
            }   
        } catch (IOException e1) {   
            e1.printStackTrace();   
        } finally {   
            try {   
                if (bos != null)   
                    bos.close();   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
        }   
        return bos.toByteArray();   
    } 
}
/**  
 * Smtp认证  
 */  
class SmtpAuthenticator1 extends Authenticator {   
    String username = null;   
    String password = null;   
  
    // SMTP身份验证   
    public SmtpAuthenticator1(String username, String password) {   
        this.username = username;   
        this.password = password;   
        System.out.println(username+"::::::"+password);
    }   
  
    public PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(this.username, this.password);   
    }   

}
 

java上传文件工具类


这个是之前整理之前所学时与使用java向邮箱发送邮件一块找到的,一起贴出来供大家参考:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UploadFile {
 
 /**
  * 按照ID和当前时间生成目录
  * @param OrderId
  * @return
  */
 public static String getAbsolutePath(){
  String currYear= new SimpleDateFormat("yyyy").format(new Date());
  String currMonth= new SimpleDateFormat("MM").format(new Date());
  String currDay = new SimpleDateFormat("dd").format(new Date());
  String path = new StringBuffer(currYear).append('/').append(currMonth).append('/').append(currDay).append('/').toString();
  return path;
  }

 /**
  * 上传课程资料
  * @param dir 文件目录
  * @param trueName 文件名称
  * @param formFile FormFile
  * @return String
  * @throws Exception
  */
 public static String uploadFile(int courseId,String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = courseId+"_"+String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 /**
  * 上传文章附件
  * @param dir
  * @param file
  * @param message
  * @return
  * @throws Exception
  */
 public static String uploadFile(String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 
 public static String uploadFile1(String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  String s=UUID.randomUUID().toString();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()+s) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 
 /**
  * @param 文件扩展名
  * @param permitFormatsConfig 文件类型
  * @return String 文件匹配类型
  */
 public static String checkFileExt(String type, String permitFormatsConfig) {
  String[] formats = permitFormatsConfig.split(";");
  for (int i = 0; i < formats.length; i++) {
   if (type.toLowerCase().endsWith(formats[i].toLowerCase())) {
    return formats[i];
   }
  }
  return null;
 }
 public static File mkdirIfNotExists(File file) {
  if (file.exists()) {
   return file;
  }
  if (file.isDirectory() && file.mkdirs()) {
   return file;
  }
  File parentDirectory = file.getParentFile();
  if (parentDirectory.exists()) {
   return file;
  } else if (parentDirectory.mkdirs()) {
   return file;
  }
  throw new java.lang.RuntimeException(
    "Failed to make some necessary parent directories. Please trying.");
 }
 
 /**
  * 上传图片,并获得缩小图片
  * 图片大小交由显示页面控制 后台将不负责修改图像大小
  * @param picDir
  * @param file
  * @param message
  * @param width
  * @return
  * @throws Exception
  */
 public static String uploadFile(String picDir, FormFile file,
   MessageResources message, int width,int height) throws Exception {
  String fileName = file.getFileName();
  int ff = fileName.lastIndexOf(".");
  ImageScale imageScale = new ImageScale();
  String logoFormat = fileName.substring(ff + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
  int imageSize = Integer.valueOf(message
    .getMessage("file.imageSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(picDir + "/" + fileName);
   mkdirIfNotExists(dirPath);// 存储位置
   InputStream stream = file.getInputStream();
   OutputStream bos = new FileOutputStream(dirPath);
   BufferedImage Bi = ImageIO.read(file.getInputStream());
   bos = new FileOutputStream(dirPath);
   //图片大小交由显示页面控制 后台将不负责修改图像大小
   /*if (Bi.getWidth() > width || Bi.getHeight() > height) {
    Bi = imageScale.imageZoomOut(Bi, width, height);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {*/
    ImageIO.write(Bi, logoFormat, dirPath);
   //}
   bos.close();
   stream.close();
   file.destroy();
   return fileName;
  } else {
   file.destroy();
   return null;
  }
 }
 
 /**
  * 上传图片,并获得缩小图片
  * @param picDir
  * @param file
  * @param message
  * @param width
  * @return
  * @throws Exception
  */
 public static String uploadFile(String picDir, FormFile file,MessageResources message, int width) throws Exception {
  String fileName = file.getFileName();
  int ff = fileName.lastIndexOf(".");
  ImageScale imageScale = new ImageScale();
  String logoFormat = fileName.substring(ff + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.imageSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "."+ logoFormat;
   File dirPath = new File(picDir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream stream = file.getInputStream();
   OutputStream bos = new FileOutputStream(dirPath);
   BufferedImage Bi = ImageIO.read(file.getInputStream());
   if (Bi.getWidth() > width || Bi.getHeight() > width) {
    Bi = imageScale.imageZoomOut(Bi, width, width);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {
    ImageIO.write(Bi, logoFormat, dirPath);
   }
   bos.close();
   stream.close();
   file.destroy();
   dirPath = new File(picDir + "/hoy_" + fileName);
   bos = new FileOutputStream(dirPath);
   if (Bi.getWidth() > 142 || Bi.getHeight() > 60) {
    Bi = imageScale.imageZoomOut(Bi, 142, 60);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {
    ImageIO.write(Bi, logoFormat, dirPath);
   }
   bos.close();
   stream.close();
   file.destroy();
   return fileName;
  } else {
   file.destroy();
   return null;
  }
 }
}
 

sql基础语句


这里是我收集的一些常用的sql语句,初学者可能记不太清楚,可以来我这边查看

1、说明:创建数据库
Create DATABASE database-name
2、说明:删除数据库
drop database dbname
3、说明:备份sql server
— 创建 备份数据的 device

USE master
EXEC sp_addumpdevice ‘disk’, ‘testBack’, ‘c:mssql7backupMyNwind_1.dat’
— 开始 备份
BACKUP DATABASE pubs TO testBack
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表:
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only
5、说明:删除新表
drop table tabname
6、说明:增加一个列
Alter table tabname add column col type
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7、说明:添加主键: Alter table tabname add primary key(col)
说明:删除主键: Alter table tabname drop primary key(col)
8、说明:创建索引:create [unique] index idxname on tabname(col….)
删除索引:drop index idxname
注:索引是不可更改的,想更改必须删除重新建。
9、说明:创建视图:create view viewname as select statement
删除视图:drop view viewname
10、说明:几个简单的基本的sql语句
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ —like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1
11、说明:几个高级查询运算词
A: UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
B: EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
C: INTERSECT 运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。
注:使用运算词的几个查询结果行必须是一致的。
12、说明:使用外连接
A、left outer join:
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
B:right outer join:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C:full outer join:
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。


hadoop从wordCount开始


最近一段时间大数据很火,我有稍微有点java基础,自然选择了由java编写的hadoop框架,wordCount是hadoop中类似于java中helloWorld的存在,自然不能错过。

package hadoop.wordcount.com;
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

  /**
   * Hadoop mapreduce中的map,用来把数据转化为map
   * @author admin
   *
   */
  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    // IntWritable是hadoop中定义的类型,相当于java中的int,这行代码相当于 int one=1;
    private final static IntWritable one = new IntWritable(1);
    // Text是hadoop中定义的类型,相当于java中的String,这行代码相当于 String text="";
    private Text word = new Text();
    
    /**
     * hadoop中继承Mapper需要实现map()方法
     * key 转化为map时输入的key,类型与Mapper第一个参数一致
     * value 转化为map时输入的value,类型与Mapper第二个参数一致
     */
    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      // 遍历输入的value,并将它们写入上下文
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  /**
   * hadoop mapreduce中的Reducer,对数据的具体操作写在这里面
   * @author admin
   *
   */
  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();
    
    /**
     * 在这里添加对数据的操作
     * key为输入类型
     * values为输出类型
     * 
     */
    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();// 读取配置文件
    Job job = Job.getInstance(conf, "word count");// 新建一个任务
    job.setJarByClass(WordCount.class);// 主类
    job.setMapperClass(TokenizerMapper.class);// mapper
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);//  reducer
    job.setOutputKeyClass(Text.class);// 输出结果的key类型
    job.setOutputValueClass(IntWritable.class);// 输出结果的value类型
    // 要读取的数据,此处内容根据你hadoop实际配置而定
    FileInputFormat.addInputPath(job, new Path("hdfs://dtj007:9000/dtj007/djt.txt"));
    //  要输出数据的路径,此处内容根据你hadoop实际配置而定
    FileOutputFormat.setOutputPath(job, new Path("hdfs://dtj007:9000/dtj007/wordcount-out"));
    System.exit(job.waitForCompletion(true) ? 0 : 1);// 提交任务
  }
}

  运行完毕以后可以在你linux配置的hadoop目录下使用:

     bin/hadoop fs -text /你在wordCount中配置的输出路径/part-r-00000

命令进行查看


android发送短信


 使用android发送短信,需要先进行添加发送,读取短信新的权限:

   

 <uses-permission

android:name="android.permission.RECEIVE_SMS"/>

<uses-permission

android:name="android.permission.SEND_SMS"/>

 接着需要在界面添加一个两个EditText,用来添加发送的号码和发送的内容,接着再加一个button用来触发发送短信的操作,代码就不贴了,直接在可视化界面拖拽即可

  然后在Activity中获取到发送按钮对象,并重写其的setOnClickListener方法,代码如下:

 

Button send=(Button)findViewById(R.id.send);

   send.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SmsManager smsManager=SmsManager.getDefault();
                Intent sendIntent=new Intent("SENT_SMS_ACTION");
                PendingIntent pi=PendingIntent.getBroadcast
                        (MainActivity.this, 0, sendIntent, 0);
                smsManager.sendTextMessage(发送的号码, null,
                        发送的内容, pi, null);
                
                
            }
        });