首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

发送邮件的源码实例!

2012-02-03 
求一个发送邮件的源码实例!急!!如题。。。不太懂发送邮件怎么做。!流程什么的也不太懂。。。求各位大大们解答[解

求一个发送邮件的源码实例!急!!
如题。。。
不太懂发送邮件怎么做。!
流程什么的也不太懂。。。
求各位大大们解答

[解决办法]
http://redleaf.iteye.com/blog/78217

[解决办法]

Java code
import java.io.UnsupportedEncodingException;  import java.util.Date;  import java.util.Properties;  import javax.mail.Address;  import javax.mail.Message;  import javax.mail.MessagingException;  import javax.mail.Session;  import javax.mail.Transport;  import javax.mail.internet.AddressException;  import javax.mail.internet.InternetAddress;  import javax.mail.internet.MimeMessage;  /**  *  邮件发送  */  public class SendMail {     /**   * 不需要验证的邮件发送   * String fromMail 发件人地址   * String password 发件人密码    * String toMail 收件人地址   * String messageText 发送的消息   * String title 发送的标题   * String serviceName 使用的邮件服务器   * @throws Exception   */   public static void setMessage(String fromMail, String toMail,     String messageText, String serviceName) throws Exception {    Properties props = System.getProperties();    props.put("mail.smtp.host", serviceName); //设置smtp的服务器地址:该邮件服务器不需要身份验证     props.put("mail.smtp.auth", "false"); //设置smtp服务器要身份验证:缺省设置为false       Address from = new InternetAddress(fromMail);    Address to = new InternetAddress(toMail);      Session session = Session.getDefaultInstance(props, null);    Message message = new MimeMessage(session);    message.setFrom(from);    message.addRecipient(Message.RecipientType.TO, to);    message.setText(messageText);      Transport.send(message);             }       /**    * 带授权的发送邮件    * String fromMail 发件人地址    * String password 发件人密码     * String toMail 收件人地址    * String messageText 发送的消息    * String title 发送的标题    * String serviceName 使用的邮件服务器    * @throws Exception     */    public static void setMessageWithAuthentica(String fromMail,String password,String toMail,String messageText,String title,String serviceName) throws Exception{    Properties props = new Properties();    props.put("mail.smtp.host",serviceName);  //设置smtp的服务器地址是smtp.sohu.com     props.put("mail.transport.protocol", "smtp");    props.put("mail.smtp.auth","true");         //设置smtp服务器要身份验证。         String formMailName=fromMail.split("@")[0];    String toMailName=toMail.split("@")[0];         PopupAuthenticator auth = new PopupAuthenticator(formMailName,fromMail);     Session session = Session.getDefaultInstance(props,auth);         session.setDebug(true);      // 发送人地址     Transport transport = null;    try {     Address addressFrom = new InternetAddress(fromMail, formMailName);     // 收件人地址      Address[] addressTo =new Address[]{new InternetAddress(toMail, toMailName)};           // 抄送地址      // Address addressCopy = new InternetAddress("123@gmail.com", "George Bush");      Message message = new MimeMessage(session);     message.setText(messageText);     message.setSubject(title);     message.setFrom(addressFrom);     message.addRecipients(Message.RecipientType.TO,addressTo);     // message.addRecipient(Message.RecipientType.CC,addressCopy);      message.saveChanges();     // session.setDebug(true);      transport = session.getTransport("smtp");  //创建连接      transport.connect(serviceName, fromMail, password);//连接服务器      transport.sendMessage(message, addressTo); //发送信息      transport.close();   //关闭连接       } catch (UnsupportedEncodingException e) {     e.printStackTrace();     Loggers.error("发送邮件错误:SendMail--setMessageWithAuthentica--UnsupportedEncodingException:"+e);    } catch (MessagingException e) {     e.printStackTrace();     Loggers.error("发送邮件错误:SendMail--setMessageWithAuthentica--MessagingException"+e);    } finally {     if(transport != null & transport.isConnected()){      transport.close();     }    }    }            public static void setMsg(String toMail, String title, String content)throws MessagingException {    Properties props = new Properties();    props.put("mail.smtp.host", "smtp.163.com");    props.put("mail.smtp.auth", "true");    Session s = Session.getInstance(props);    s.setDebug(true);      MimeMessage message = new MimeMessage(s);    Transport transport = null;    try {     InternetAddress from = new InternetAddress("xxx@163.com");     message.setFrom(from);     InternetAddress to = new InternetAddress(toMail);     message.setRecipient(Message.RecipientType.TO, to);     message.setSubject(title);     message.setText(content);     message.setSentDate(new Date());     message.saveChanges();     transport = s.getTransport("smtp");     transport.connect("smtp.163.com", "xxx", "xxx");     transport.sendMessage(message, message.getAllRecipients());     transport.close();    } catch (AddressException e) {     e.printStackTrace();     Loggers.error("发送邮件错误:SendMail--setMsg--AddressException:" + e);    } catch (MessagingException e) {     e.printStackTrace();     Loggers.error("发送邮件错误:SendMail--setMsg--MessagingException:" + e);    } finally {     if (transport != null & transport.isConnected()) {      transport.close();     }    }   }        public static void main(String[] args){     try {      SendMail.setMessageWithAuthentica("您的邮箱", "您的密码", "对方邮箱", "邮件内容", "邮件标题", "服务器地址");    } catch (Exception e) {     e.printStackTrace();    }    }  } 


[解决办法]

Java code
package com.asql.base;import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;public class MailSender {  public final static boolean sendMail(LoadLog sendlog,String smtphost,String mailfrom,  boolean mailauth,String mailuser,String mailpassword,  String mailto,String mailcc,String mailsubject,  String mailmessage,String mailattach) { MimeMessage mimeMsg;  MimeMultipart mp;         Session session;      String sep[]={";"}; Properties props=new java.util.Properties();     int i; props.put("mail.smtp.host",smtphost); try{      session = Session.getDefaultInstance(props,null);       mimeMsg = new MimeMessage(session);      mp = new MimeMultipart();      if(mailauth)       props.put("mail.smtp.auth","true");        else         props.put("mail.smtp.auth","false");      if (sendlog!=null)  sendlog.println("Mail Host Address: "+smtphost); } catch(Exception e) {      if (sendlog!=null)       sendlog.println(e.getMessage());      return false;   } try {      mimeMsg.setFrom(new InternetAddress(mailfrom));       if (sendlog!=null)       sendlog.println("Mail From Address: "+mailfrom); } catch(Exception e)    {      if (sendlog!=null)       sendlog.println(e.getMessage());      return false;  } try{     java.util.Vector temp = WordsConvert.getWords(mailto,sep);     if (temp.size()==0)     {         if (sendlog!=null)   sendlog.println("Mail Target Address Requried.");  return false;     }     Address toaddress[] = new Address[temp.size()];     for(i=0;i<temp.size();i++)  toaddress[i]=InternetAddress.parse(temp.elementAt(i).toString())[0];      mimeMsg.setRecipients(Message.RecipientType.TO,toaddress);            if (sendlog!=null)      sendlog.println("Mail To   Address: "+mailto); } catch(Exception e) {            if (sendlog!=null)      sendlog.println("Error Mail To,"+e);     return false;        }        if(mailcc != null && mailcc.length()>0) {  try{      java.util.Vector temp = WordsConvert.getWords(mailcc,sep);      if (temp.size()>0)      {       Address ccaddress[] = new Address[temp.size()];       for(i=0;i<temp.size();i++)    ccaddress[i]=InternetAddress.parse(temp.elementAt(i).toString())[0];        mimeMsg.setRecipients(Message.RecipientType.CC,ccaddress);              if (sendlog!=null)        sendlog.println("Mail Cc   Address: "+mailcc);      }  }  catch(Exception e)  {             if (sendlog!=null)       sendlog.println(e.getMessage());      return false;         } } try {   mimeMsg.setSubject(mailsubject,"GB2312");  BodyPart bp = new MimeBodyPart();  bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+    mailmessage,"text/html;charset=GB2312");  mp.addBodyPart(bp); } catch(Exception e)  {            if (sendlog!=null)  sendlog.println(e.getMessage());     return false;    }        if(mailattach != null && mailattach.length()>0) {  try{       java.util.Vector temp = WordsConvert.getWords(mailattach,sep);       for(i=0;i<temp.size();i++)       {        MimeBodyPart bp = new MimeBodyPart();        FileDataSource fileds = new FileDataSource(temp.elementAt(i).toString());        DataHandler dh = new DataHandler(fileds);        bp.setDisposition(Part.ATTACHMENT);        bp.setFileName(fileds.getName());        bp.setDataHandler(dh);        mp.addBodyPart(bp);       }  }  catch(Exception e)  {   if (sendlog!=null)        sendlog.println(e.getMessage());        return false;  } } try{      mimeMsg.setContent(mp);      mimeMsg.saveChanges();      Session mailSession = Session.getInstance(props,null);      Transport transport = mailSession.getTransport("smtp");      transport.connect((String)props.get("mail.smtp.host"),mailuser,mailpassword);      transport.sendMessage(mimeMsg,mimeMsg.getAllRecipients());      if (sendlog!=null)       sendlog.println("Mail Successfully Sended!");      transport.close(); } catch(Exception e) {      if (sendlog!=null)       sendlog.println(e.getMessage());;      return false ; } return true;   }} 

热点排行