MailServer.properties 属性文件SmtpHost=smtp.sohu.com
User=这里是你的邮箱用户名请改为自己的
Password=你的密码
Sender=你的邮箱
Subject=my first java mail
发送邮件的类import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
 * 发送邮件
 * @author xiao
 *
 */
public class SendMail {
private String errMsg = ""; private ExtendString ExStr = new ExtendString(); private String sender = "";// 发件人地址 private String smtpHost = "";// 邮件发送服务器(smtp) private String user = ""; // 登录用户名 private String password = "";// 登录密码 private String subject = "";// mail主题 public SendMail() {
this.setPropertiesAttri();
} private void setPropertiesAttri() {
try {
InputStream is = getClass().getResourceAsStream("MailServer.properties");
Properties prop = new Properties();

prop.load(is); this.setSmtpHost(prop.get("SmtpHost").toString());
this.setUser(prop.get("User").toString());
this.setPassword(prop.get("Password").toString());
this.setSender(prop.get("Sender").toString());
this.setSubject(ExStr.CS(prop.get("Subject").toString()));
} catch (Exception ex) {
System.err.println("ex1 in sendmail.java:" + ex.toString());
}
} /** 设置发件人地址 */ public void setSender(String sender) {
this.sender = sender;
} public String getSender() {
return sender;
} /** 设置邮件发送服务器(smtp) */ public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
} public String getSmtpHost() {
return smtpHost;
} /** 设置登录用户名 */
public void setUser(String user) {
this.user = user;
} public String getUser() {
return user;
} /** 设置登录密码 */
public void setPassword(String password) {
this.password = password;
} public String getPassword() {
return password;
} /** 设置mail主题 */
public void setSubject(String subject) {
this.subject = subject;
} public String getSubject() {
return subject;
} /**
 * 使用smtp发送邮件 主程序
 * 
 * @throws MessagingException
 *             mail发送失败
 */
public void smtp(String receiver, String content) throws MessagingException {
if (smtpHost == null)
throw new MessagingException("smtpHost not found");
if (user == null)
throw new MessagingException("user not found");
if (password == null)
throw new MessagingException("password not found"); Properties properties = new Properties(); properties.put("mail.smtp.host", smtpHost);// 设置smtp主机
properties.put("mail.smtp.auth", "true");// 使用smtp身份验证 Session session = Session.getDefaultInstance(properties,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}); // 获得邮件会话对象
MimeMessage mimeMsg = new MimeMessage(session);// 创建MIME邮件对象
if (sender != null)// 设置发件人地址
{
mimeMsg.setFrom(new InternetAddress(sender));
}
if (receiver != null)// 设置收件人地址
{
// mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver));
mimeMsg.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
}
if (subject != null)// 设置邮件主题
{
mimeMsg.setSubject(subject, "GBK"); }
MimeBodyPart part = new MimeBodyPart();// mail内容部分
part.setText(content == null ? "" : content, "GBK"); // 设置邮件格式为html cqc
part.setContent(content.toString(), "text/html;charset=GBK");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(part);// 在 Multipart 中增加mail内容部分
mimeMsg.setContent(multipart);// 增加 Multipart 到信息体
mimeMsg.setSentDate(new Date());// 设置发送日期
System.out.println("邮件发送中");
//mimeMsg.getRecipients(Message.RecipientType.TO);
System.out.println(receiver);
Transport.send(mimeMsg);// 发送邮件
System.out.println("邮件发送成功");
} /** 解析地址集合字符串 */
private InternetAddress[] parse(String addressSet) throws AddressException {
ArrayList list = new ArrayList();
StringTokenizer tokens = new StringTokenizer(addressSet, ";");
while (tokens.hasMoreTokens()) {
list.add(new InternetAddress(tokens.nextToken().trim()));
}
InternetAddress[] addressArray = new InternetAddress[list.size()];
list.toArray(addressArray);
InternetAddress add=(InternetAddress) list.get(0);
System.out.println(add.getAddress());
return addressArray;
} // 供外部调用的接口
public boolean sendMails(String mail, String content) {
int mailLen = 0; int contentLen = 0;
if (mail == null || content == null) {
return false;
} try {
this.smtp(mail, content);
} catch (Exception ex) {
System.err.println("ex2 in sendmail.java:" + ex.toString());
} return true;
} public static void main(String[] args) {
SendMail mail = new SendMail();
String email = "[email protected]";  //接收邮件的邮箱地址
String content = " the context ";  //内容
try {
mail.sendMails(email, content);
} catch (Exception ex) {
System.err.println("ex33:" + ex.toString());
}
}}
/**
 * 字符串的操作
 * @author xiao
 *
 */
class ExtendString {
public ExtendString() {
}
/**
 * 去掉字符串两端的空白字符,并将字符串转化为中国的标准字符gb2312的字符串.
 */
public static String CS(String str) { // 去掉字符串2端的空白字符
try {
if (str == null)
return "";
str = str.trim();
if (str == null)
return "";
str = new String(str.getBytes("8859_1"), "GBK");
} catch (Exception e) {
System.out.println(e);
}
return str;
}}这个邮件发送不出去啊,它提示邮件发出去了,可是我去我邮箱看,确没有邮件,请各位帮忙看看,运行运行看看行不
我这个例子是从网上找来的

解决方案 »

  1.   

    有延迟?换一个smtp服务器试试。比如163或qq的邮箱
      

  2.   

    http://blog.csdn.net/sunyujia/archive/2008/06/10/2528696.aspx
    试试我的,反正你都是在网上找的,不一定能保证可用性。package com.syj;import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Properties;import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.Authenticator;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    /**
     * <P>
     * Title:用java发送邮件的例子
     * </P>
     * 
     * <P>
     * Description:发送图片附件并在html中使用该图片
     * </P>
     * 
     * <P>
     * Copyright: Copyright (c) 2007
     * </P>
     * 
     * @author 孙钰佳 
     * @blog http://blog.csdn.net/sunyujia/
     * @main [email protected]
     * @date Jun 10, 2008 12:35:26 AM
     */
    public class SendMail {
    private static String username = "xxxx";
    private static String password = "xxxx";
    private static String smtpServer = "smtp.163.com";
    private static String fromMailAddress = "[email protected]";
    private static String toMailAddress = "[email protected]"; public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", smtpServer);
    // 获得邮件会话对象
    Session session = Session.getDefaultInstance(props,
    new SmtpAuthenticator(username, password));
    /** *************************************************** */
    // 创建MIME邮件对象
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
    toMailAddress));// 收件人
    mimeMessage.setSubject("主题");
    mimeMessage.setSentDate(new Date());// 发送日期
    Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
    /** *************************************************** */
    BodyPart bodyPart = new MimeBodyPart();// 正文
    bodyPart.setDataHandler(new DataHandler("测<img src=\"cid:IMG1\" />试",
    "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("C:/button.gif");
    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);// 设置邮件内容对象
    Transport.send(mimeMessage);// 发送邮件 } /**
     * 读取文件
     * 
     * @param file
     *            文件路径
     * @return 返回二进制数组
     */
    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 SmtpAuthenticator extends Authenticator {
    String username = null;
    String password = null; // SMTP身份验证
    public SmtpAuthenticator(String username, String password) {
    this.username = username;
    this.password = password;
    } public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(this.username, this.password);
    }}
    class ByteArrayDataSource implements DataSource { private final String contentType;
    private final byte[] buf;
    private final int len; public ByteArrayDataSource(byte[] buf, String contentType) {
    this(buf, buf.length, contentType);
    } public ByteArrayDataSource(byte[] buf, int length, String contentType) {
    this.buf = buf;
    this.len = length;
    this.contentType = contentType;
    } public String getContentType() {
    if (contentType == null)
    return "application/octet-stream";
    return contentType;
    } public InputStream getInputStream() {
    return new ByteArrayInputStream(buf, 0, len);
    } public String getName() {
    return null;
    } public OutputStream getOutputStream() {
    throw new UnsupportedOperationException();
    }
    }
      

  3.   

    不知是否跟本机的环境有没有问题?我发送邮件前是否要对自己机子的环境要设置什么呢?
    我觉得这样的代码也没有问题啊3楼的同志,我使用你的程序了,在我这运行也有错误Exception in thread "main" javax.mail.SendFailedException: Sending failed;
      nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at demo2.SendMail.main(SendMail.java:100)在我这是验证没通,我不知要怎么验证,不就是有用户名和密码就OK了吗?
      

  4.   

    来人说说原因吧,please Hellp me!
      

  5.   

    晕不是又是老问题吧
    http://topic.csdn.net/u/20081011/19/73d55020-a826-46f7-ace0-084c2f1f18c5.html你没使用stmp的权限,你是新注册的用户吧。
      

  6.   

    学习了~以前也遇到过,是因为本地的IIS有延迟在邮件Queue文件夹下面有那些邮件
      

  7.   

    即使有延迟,那它延迟过后也该发出去吧,可是我等了一天,也不见我的邮箱有内容啊
    弱弱的问一下 Queue文件夹 在哪啊
      

  8.   

    新用户不行,你没看我给你的帖子吗?为何新申请的邮箱不能用客户端?字体: 小 中 大 
      目前免费邮箱新注册的用户不支持直接开通smtp、pop3的服务,之前已开通客户端功能的老用户不受影响。如果需要使用该功能,您可以选择 VIP邮箱,另外我们也会陆续通过“积分活动”、“邮箱会员”等方式也会向有需要的用户提供该项服务,敬请关注。同时感谢您使用我们的产品! http://help.163.com/07/0524/10/3F8K8I6V007525G0.html
      

  9.   

    你去申请个雅虎.cn的
    服务器地址(国外的国内的地址也不支持)
    smtp.mail.yahoo.com或者申请个@foxmail.com
       目前几乎90%的免费邮箱不提供smtp支持.楼主不要在看技术了,多关注下服务商.