我是一边看视频做的,看的是传智播客的视频,怎么知道他们成功了,看代码
public static void main(String[] args) throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");//使用smtp协议
Session session = Session.getInstance(props);
session.setDebug(true);//加入调式
Message msg = new MimeMessage(session);//信息
msg.setText("efefwfe");//信息内容
msg.setFrom(new InternetAddress("lisi@qq.com"));//发件人
Transport transport = session.getTransport();
transport.connect("smtp.qq.com", 25, "379954476@qq.com",
"password");//连接(smtp服务器,端口,发件人登陆,密码)
transport.sendMessage(msg, new Address[] { new InternetAddress(
"xusenjian@sohu.com") });//发送信息,地址
transport.close();
}
上面的发件人如果跟发件人登录的账户不同的话,便报了个错
Exception in thread "main" com.sun.mail.smtp.SMTPSendFailedException: 501 mail from address must be same as authorization user
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at cn.itcast.javamail.Demo.main(Demo.java:33)
com.sun.mail.smtp.SMTPSendFailedException: 501 mail from address must be same as authorization user
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at cn.itcast.javamail.Demo.main(Demo.java:33)
他们做的时候,是可以把发件人设置成跟登陆名不同的名字的,为什么我一设置就报错,程序是一模一样的
------最佳解决方案--------------------
刚才我测试了一下,是可以的。代码如下,我用的是spring封装的类。
import java.io.File;
import java.util.Properties;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SendMailTest {
public static void main(String[] args) {
try{
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//MimeMessage msg = senderImpl.createMimeMessage();
//MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
//设定mail server
senderImpl.setHost("127.0.0.1");
senderImpl.setUsername("1000") ; // 根据自己的情况,设置username
senderImpl.setPassword("123456") ; // 根据自己的情况, 设置password
Properties prop = new Properties() ;
prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
prop.put("mail.smtp.timeout", "25000") ;
senderImpl.setJavaMailProperties(prop);
//建立邮件消息,发送简单邮件和html邮件的区别
MimeMessage mailMessage = senderImpl.createMimeMessage();
//注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,