疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java实现邮件的发送分享


 

        java实现邮件的发送分享方法如下:

  public class PopupAuthenticator extends Authenticator{

  public PasswordAuthentication getPasswordAuthentication()

  {

  String username="11111111@qq.com"; //邮箱登录帐号

  String pwd = "111111"; //登录密码

  return new PasswordAuthentication(username,pwd);

  }

  }

  public class SendMail {

  public static void main(String[] args) {

  try {

  Authenticator auth = new PopupAuthenticator();

  Properties mailProps = new Properties();

  //邮件信息验证

  mailProps.put("mail.smtp.host", "smtp.qq.com");

  mailProps.put("mail.smtp.auth", "true");

  mailProps.put("username", "111111@qq.com"); //用户名

  mailProps.put("password", "111111");//密码

  Session mailSession = Session.getDefaultInstance(mailProps, auth);

  MimeMessage message = new MimeMessage(mailSession);

  message.setFrom(new InternetAddress("22222222@qq.com"));//发件人地址

  Address toInternetAddress=new InternetAddress("wwwwww@qq.com");//收件人地址

  message.setRecipient(Message.RecipientType.TO, toInternetAddress);

  message.setSubject("Mail Test"); //邮件标题

  message.setSentDate(new Date()); // 设置邮件发送日期

  MimeMultipart multi = new MimeMultipart();

  BodyPart textBodyPart = new MimeBodyPart();

  //textBodyPart.setText("Hello World!"); //邮件内容

  multi.addBodyPart(textBodyPart);

  message.setContent(multi);

  message.saveChanges();

  //下面代码是发送附件

  String fileName = "E:/hello.txt"; //发送附件的文件路径

  MimeBodyPart messageBodyPart = new MimeBodyPart();

  messageBodyPart.setText("Hi there is message info "); //邮件内容

  Multipart multipart = new MimeMultipart();

  multipart.addBodyPart(messageBodyPart);

  messageBodyPart = new MimeBodyPart();

  DataSource source = new FileDataSource(fileName);

  messageBodyPart.setDataHandler(new DataHandler(source));

  messageBodyPart.setFileName(fileName);

  multipart.addBodyPart(messageBodyPart);

  message.setContent(multipart);

  //推送邮件和附件信息

  Transport.send(message);

  System.out.println("---------邮件发送成功----------");

  } catch (Exception ex) {

  System.err.println("邮件发送失败的原因是:" + ex.getMessage());

  System.err.println("具体错误原因:");

  ex.printStackTrace(System.err);

  }

  }

  }