DEBUG: setDebug: JavaMail version 1.3.1
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.sina.com", port 25220 irxd5-201.sinamail.sina.com.cn ESMTP
DEBUG SMTP: connected to host "smtp.sina.com", port: 25EHLO
501 #5.0.0 EHLO requires domain address
HELO
250 irxd5-201.sinamail.sina.com.cn
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
javax.mail.MessagingException: 530 Authentication required at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
at mail.SendMail.send(SendMail.java:81)
at mail.SendMail.main(SendMail.java:163)
530 Authentication required
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.sina.com", port 25220 irxd5-201.sinamail.sina.com.cn ESMTP
DEBUG SMTP: connected to host "smtp.sina.com", port: 25EHLO
501 #5.0.0 EHLO requires domain address
HELO
250 irxd5-201.sinamail.sina.com.cn
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
javax.mail.MessagingException: 530 Authentication required at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
at mail.SendMail.send(SendMail.java:81)
at mail.SendMail.main(SendMail.java:163)
530 Authentication required
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddr = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO, toAddr);
message.setContent(content, "text/html;charset=gb2312");
message.setSubject(subject);
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddr = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO, toAddr);
message.setContent(content, "text/html;charset=gb2312");
message.setSubject(subject);
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
SendMail sendmail = new SendMail();
sendmail.setHost("smtp.sina.com");// 你的邮件服务器
sendmail.setUser("jiangchaozeng"); // 你的用户名
sendmail.setPassword("523762663"); // 你的密码
sendmail.setFrom("[email protected]");// 你的邮件地址
sendmail.send("[email protected]", "第一封邮件", "邮件内容");
System.out.print("mail has send.");
}
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
MyAuthenticator authenticator = new MyAuthenticator(name, psw);
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
public void send(String to, String subject, String content) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
MyAuthenticator authenticator = new MyAuthenticator(user, password);
Session mailSession = Session.getDefaultInstance(props,authenticator);
mailSession.setDebug(true);
try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddr = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO, toAddr);
message.setContent(content, "text/html;charset=gb2312");
message.setSubject(subject);
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
SendMail sendmail = new SendMail();
sendmail.setHost("smtp.sina.com");// 你的邮件服务器
sendmail.setUser("[email protected]"); // 你的用户名
sendmail.setPassword("523762663"); // 你的密码
sendmail.setFrom("[email protected]");// 你的邮件地址
sendmail.send("[email protected]", "第一封邮件", "邮件内容");
/*sendmail.send(
"[email protected]",
"附件2!",
"这是内容",
"C:\\Documents and Settings\\Administrator\\桌面\\c3p0-0.9.1.2.src.zip");// 带附件的邮件,把附件路径改成你的路径
*/
System.out.print("mail has send.");
import java.util.Properties;
import javax.servlet.*; //此句报错误的话请注释
import javax.mail.Session;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Transport;
public class javaMail {
private Properties properties;
private Session mailSession;
private MimeMessage mailMessage;
private Transport trans;
public javaMail() {
}
public void sendMail() {
try {
properties = new Properties();
//设置邮件服务器
properties.put("mail.smtp.host", "smtp.sina.com");
//验证
properties.put("mail.smtp.auth", "true");
//根据属性新建一个邮件会话
mailSession = Session.getInstance(properties,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]",
"*******");
}
});
mailSession.setDebug(true);
//建立消息对象
mailMessage = new MimeMessage(mailSession);
//发件人
mailMessage.setFrom(new InternetAddress("[email protected]"));
//收件人
mailMessage.setRecipient(MimeMessage.RecipientType.TO,
new InternetAddress("[email protected]"));
//主题
mailMessage.setSubject("测试");
//内容
mailMessage.setText("test");
//发信时间
mailMessage.setSentDate(new Date());
//存储信息
mailMessage.saveChanges();
//
trans = mailSession.getTransport("smtp");
//发送
trans.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
javaMail javaMail=new javaMail();
javaMail.sendMail();
}
}
我从别处找来的,你试试看这个行不?我看代码也差不多啊.你好像就多了个close,你先试试这个看看
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 500 Error: bad syntax at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at mail.javaMail.sendMail(javaMail.java:55)
at mail.javaMail.main(javaMail.java:68)
http://commons.apache.org/email/ 他里面也有认 API(org.apache.commons.mail.DefaultAuthenticator),记得写上对了你除了要有mail.jar ,还要有activation.jar(很重要的包) 顺便期待其他高手出现把。呵呵
String userName = null;
String password = null;
public Auth(){
}
public Auth(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
package chuwa.com.cn;
import java.io.IOException;
import java.util.Properties;import org.jdom.*;
import org.jdom.input.SAXBuilder;public class MailSenderInfo {
//
private String mailServerHost;
private String mailServerPort;
private String userName = "*****@163.com";
private String password = "*****";
private String from;
private String fromAddress;
private String toAddress;
private String subject;
private String content;
public Properties getProperties(){
//读取mail.xml中的配置设定
Document mailDoc = new Document();
SAXBuilder builder = new SAXBuilder();
try {
mailDoc = builder.build(this.getClass().getResource("/").getPath()
+ "MAIL.xml");
} catch (JDOMException jex) { } catch (IOException iex) {
iex.printStackTrace();
}
Element eRoot = mailDoc.getRootElement();
mailServerHost = eRoot.getChildText("MAIL_SERVER_HOST");
mailServerPort = eRoot.getChildText("MAIL_SERVER_PORT");
userName = eRoot.getChildText("MAIL_SERVER_USER");
password = eRoot.getChildText("MAIL_SERVER_PASSWORD");
from = eRoot.getChildText("MAIL_FROM");
fromAddress = eRoot.getChildText("MAIL_FROM_ADDRESS");
Properties p = new Properties();
p.put("mail.smtp.host", mailServerHost);
p.put("mail.smtp.port", mailServerPort);
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.user", userName);
p.put("mail.smtp.password", password);
return p;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
import java.util.Properties;import javax.mail.*;
import javax.mail.internet.*;public class SimpleMailSender {
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
Properties p = mailInfo.getProperties();
Auth auth = new Auth(p.getProperty("mail.smtp.user"), p.getProperty("mail.smtp.password")); Session sendMailSession = Session.getInstance(p,auth);
try{
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress(),mailInfo.getFrom());
mailMessage.setFrom(from);
Address[] to = null;
String[] addresses = mailInfo.getToAddress().split(";");
to = new Address[addresses.length];
for(int i=0;i<addresses.length;i++){
to[i] = new InternetAddress(addresses[i]);
}
mailMessage.setRecipients(Message.RecipientType.TO, to);
String subject = mailInfo.getSubject();
mailMessage.setSubject( MimeUtility.encodeText( subject,"UTF-8","B")); mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
String content = mailInfo.getContent();
html.setContent(content,"text/html;charset=UTF-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
return true;
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
public static boolean sendTextMail(MailSenderInfo mailInfo){
Session sendMailSession = Session.getInstance(mailInfo.getProperties());
try{
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address[] to = null;
String[] addresses = mailInfo.getToAddress().split(";");
to = new Address[addresses.length];
for(int i=0;i<addresses.length;i++){
to[i] = new InternetAddress(addresses[i]);
}
mailMessage.setRecipients(Message.RecipientType.TO, to);
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
mailMessage.setText(mailInfo.getContent());
Transport.send(mailMessage);
return true;
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<SCSERP_MAIL>
<!--发送邮件服务器地址-->
<MAIL_SERVER_HOST>smtp.163.com</MAIL_SERVER_HOST>
<!--发送邮件服务器端口-->
<MAIL_SERVER_PORT>25</MAIL_SERVER_PORT>
<!--发送邮件服务器用户-->
<MAIL_SERVER_USER>*****@163.com</MAIL_SERVER_USER>
<!--发送邮件服务器密码-->
<MAIL_SERVER_PASSWORD>*****</MAIL_SERVER_PASSWORD>
<!--发送邮件方-->
<MAIL_FROM></MAIL_FROM>
<!--发送邮件方地址-->
<MAIL_FROM_ADDRESS>*****@163.com</MAIL_FROM_ADDRESS>
</SCSERP_MAIL>
且据说发送邮件方地址应和发送邮件服务器用户一致,否则auth会失败
MailSenderInfo mailInfo = new MailSenderInfo();mailInfo.setToAddress(strTo);
mailInfo.setSubject(strSubject);
mailInfo.setContent(strBody.replaceAll("\r\n","<br>"));
SimpleMailSender.sendHtmlMail(mailInfo);把xml里的<!--发送邮件服务器用户-->
<MAIL_SERVER_USER>*****@163.com </MAIL_SERVER_USER>
<!--发送邮件服务器密码-->
<MAIL_SERVER_PASSWORD>***** </MAIL_SERVER_PASSWORD>
<!--发送邮件方-->
<MAIL_FROM>name</MAIL_FROM>
<!--发送邮件方地址-->
<MAIL_FROM_ADDRESS>*****@163.com </MAIL_FROM_ADDRESS>
改成你自己注册的163用户名以及密码难道要我注册一个给你?
javax.mail.MessagingException: 500 Error: bad syntax at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1363)
at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:838)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:375)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at SimpleMailSender.sendHtmlMail(SimpleMailSender.java:52)
at Test.main(Test.java:8)
[email protected] 密码password,我运行过了,邮件已经在里面了不是吗
另外,我的环境是jdk1.6,windows,这个肯定没有问题
你如果是在linux下直接运行这个确实可能会报500错误的
据说要在/etc/hosts文件中加入 127.0.0.1 myhostname
如果是web项目两个jar在容器中的位置要同级
例如,我在web项目下发送mail,我的jboss\server\default\lib下同时有这两个jar
不过,我在java项目里发送mail只用了mail.jar,一样成功了.
如果你不是在web项目下,那我不知道你的失败原因了,你去掉不需要的jar试试,
难道是包的冲突?
另外,领导在的时候不能Q,
可以发送邮件。import java.util.Properties;import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;public class MailTransfor {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
// 要使用用户名,密码进行认证登录,如果是直接给smtp服务器发就不用这个了
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
//props.setProperty("mail.transport.protocol", "openssl");
//props.setProperty("mail.store.protocol", "openssl");
Session session = Session.getInstance(props);
session.setDebug(true); String str = "adfasdfasdfasdf";
Message message = new MimeMessage(session);
message.setText(str);
message.setSubject("对不起");
message.setFrom(new InternetAddress("[email protected]", "=|=")); // transport的一些信息保存在session里
Transport transport = session.getTransport();
// *********qqNumber是qq号码,例如888888,password是qq的密码
transport.connect("smtp.qq.com", 465, "qqNumber", "password");
// *********发送邮件到[email protected]
transport.sendMessage(message, InternetAddress.parse("[email protected]"));
transport.close();
}
}
transport.sendMessage(message, InternetAddress.parse("[email protected]"));
停止了
报了一个这样的错:
DEBUG SMTP: exception reading response: java.net.SocketException: Connection reset
Exception in thread "main" javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1090)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:986)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
at javax.mail.Service.connect(Service.java:233)
at mail.MailTransfor.main(MailTransfor.java:31)
struts2 action类部分代码:
public String forgetPassword() throws Exception {
String host = "smtp.sina.com";
String username = "*****@sina.com";//登陆sina的邮箱用户名
String password = "****";//登陆sina的邮箱密码
String userPassword = userService.validateEmail(user.getEmail()); //这个是我这个模块的功能,和你应该没什么关系
HtmlSender mail = new HtmlSender(host,username,password);
mail.setFrom("****@sina.com");//跟上面的一样。表示从这个邮箱往外发邮件
mail.setTo(user.getEmail());
mail.setSubject("IN不IN网站用户找回密码");
mail.setContent("尊敬的用户:<b>你的密码是:"+userPassword+"!<br>请做好保密工作!!!");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html");
response.setCharacterEncoding("gbk");
if(mail.send()){
return "ok";
}else{
return "no";
}
}
HtmlSender.javaimport java.io.UnsupportedEncodingException;
import java.util.Properties;import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;public class HtmlSender { private MimeMessage message;
private Properties props;
private Session session;
private MimeMultipart part;
private String username;
private String password;
public HtmlSender(String host,String username,String password){
this.username = username;
this.password = password;
props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
MyAuthenticator auth = new MyAuthenticator(username,password);
session = Session.getDefaultInstance(props, auth);
message = new MimeMessage(session);
part = new MimeMultipart();
}
public void setFrom(String from){
try {
message.setFrom(new InternetAddress(from));
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void setTo(String to){
try {
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void setSubject(String subject){
try {
message.setSubject(MimeUtility.encodeText(subject));
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void setContent(String content){
try {
message.setContent(content, "text/html;charset=gb2312");
message.saveChanges();
} catch (MessagingException e) {
e.printStackTrace();
}
}你试下吧
需要javamail相关的jar
public boolean send(){
try {
Transport port = session.getTransport("smtp");
port.connect(props.getProperty("mail.smtp.host"), username, password);
port.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
port.close();
return true;
} catch (NoSuchProviderException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
}
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;public class MailTransfor {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true"); // 要使用用户名,密码进行认证登录,如果是直接给smtp服务器发就不用这个了
props.setProperty("mail.transport.protocol", "smtp");
//props.setProperty("mail.transport.protocol", "openssl");
//props.setProperty("mail.store.protocol", "openssl");
Session session = Session.getInstance(props);
session.setDebug(true); String str = "是我做得不好";
Message message = new MimeMessage(session);
message.setText(str);
message.setSubject("对不起");
message.setFrom(new InternetAddress("[email protected]", "黄彪")); Transport transport = session.getTransport(); // transport的一些信息保存在session里
transport.connect("smtp.qq.com", 25, "qqNumber", "password"); // 不好意思, 端口号是25, 以前改成465, 是为了测试google的帐号
transport.sendMessage(message, InternetAddress.parse("[email protected]"));
transport.close();
}
}这个程序没有任何问题了, 刚才我发送过, 发送成功.
535 Auth failed System Error
Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:264)
at mail.MailTransfor.main(MailTransfor.java:31)
-----
message.setFrom(new InternetAddress("[email protected]", "=|="));第一个参数可以随便写撒
-----
transport.connect("smtp.qq.com", 25, "523762663", "******"); 这个就是这样的写
-----
transport.sendMessage(message, InternetAddress.parse("[email protected]"));
以上就是我的写法 这样子可以吗 上面的都和你一样的。
//Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
//final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "192.168.0.7");
//props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
//props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "25");
//props.setProperty("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.auth", "true");
final String username = "WM_Reminder";
final String password = "Qwert,2001";
Session session = Session.getDefaultInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
}); //Create a new message --
Message msg = new MimeMessage(session);
//Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
if(to.startsWith(",")){
to = to.substring(1);
}
if(to.endsWith(",")){
to = to.substring(0, to.length()-1);
}
InternetAddress[] toList = new InternetAddress().parse(to);
msg.setRecipients(Message.RecipientType.TO, toList);
msg.setSubject(subject); //Set the content
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(text, "text/html; charset=utf-8");
mainPart.addBodyPart(html);
msg.setContent(mainPart);
Transport.send(msg);
System.out.println("Success!");
}
catch (MessagingException e) {
e.printStackTrace();
}公司内部的发邮件,(如果要用Gmail的,就把注释掉的还原)
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 Authentication required at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at mail.SendMail4.main(SendMail4.java:57)
-----------
代码是这样的Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.sina.com");
props.setProperty("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
final String username = "jiangchaozeng";
final String password = "******";
Session session = Session.getDefaultInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
InternetAddress[] toList = new InternetAddress().parse("[email protected]");
msg.setRecipients(Message.RecipientType.TO, toList);
msg.setSubject("主题");
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent("邮件内容", "text/html; charset=utf-8");
mainPart.addBodyPart(html);
msg.setContent(mainPart);
Transport.send(msg);
System.out.println("Success!");
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
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;public class MailSend {
//要发送Mail地址 private String mailTo = "[email protected]"; //Mail发送的起始地址 private String mailFrom = null; //SMTP主机地址 private String smtpHost = "smtp.163.com"; //是否采用调试方式 private boolean debug = false; private String messageBasePath = null; //Mail主题 private String subject; //Mail内容 private String msgContent; private Vector attachedFileList; private String mailAccount = null; private String mailPass = ""; private String messageContentMimeType ="text/html; charset=gb2312"; private String mailbccTo = null; private String mailccTo = null; /** * SendMailService 构造子注解。 */
private void fillMail(Session session,MimeMessage msg) throws IOException, MessagingException{ String fileName = null; Multipart mPart = new MimeMultipart(); if (mailFrom != null) { msg.setFrom(new InternetAddress(mailFrom)); System.out.println("发送人Mail地址:"+mailFrom); } else { System.out.println("没有指定发送人邮件地址!"); return; } if (mailTo != null) { InternetAddress[] address = InternetAddress.parse(mailTo); msg.setRecipients(Message.RecipientType.TO, address); System.out.println("收件人Mail地址:"+mailTo); } else { System.out.println("没有指定收件人邮件地址!"); return; } if (mailccTo != null) { InternetAddress[] ccaddress = InternetAddress.parse(mailccTo); System.out.println("CCMail地址:"+mailccTo); msg.setRecipients(Message.RecipientType.CC, ccaddress); } if (mailbccTo != null) { InternetAddress[] bccaddress = InternetAddress.parse(mailbccTo); System.out.println("BCCMail地址:"+mailbccTo); msg.setRecipients(Message.RecipientType.BCC, bccaddress); } msg.setSubject(subject); InternetAddress[] replyAddress = { new InternetAddress(mailFrom)}; msg.setReplyTo(replyAddress); // create and fill the first message part MimeBodyPart mBodyContent = new MimeBodyPart(); if (msgContent != null) mBodyContent.setContent(msgContent, messageContentMimeType); else mBodyContent.setContent("", messageContentMimeType); mPart.addBodyPart(mBodyContent); // attach the file to the message if (attachedFileList != null) { for (Enumeration fileList = attachedFileList.elements(); fileList.hasMoreElements();) { fileName = (String) fileList.nextElement(); MimeBodyPart mBodyPart = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(messageBasePath + fileName); System.out.println("Mail发送的附件为:"+messageBasePath + fileName); mBodyPart.setDataHandler(new DataHandler(fds)); mBodyPart.setFileName(fileName); mPart.addBodyPart(mBodyPart); } } msg.setContent(mPart); msg.setSentDate(new Date()); } /** * 此处插入方法说明。 */ public void init() { } /** * 发送e_mail,返回类型为int * 当返回值为0时,说明邮件发送成功 * 当返回值为3时,说明邮件发送失败 */ public int sendMail() throws IOException, MessagingException { int loopCount; Properties props = System.getProperties(); props.put("mail.smtp.host", "smtp.163.com"); props.put("mail.smtp.auth", "true"); MailAuthenticator auth = new MailAuthenticator(); Session session = Session.getInstance(props, auth); session.setDebug(debug); MimeMessage msg = new MimeMessage(session); Transport trans = null; try { fillMail(session,msg); // send the message trans = session.getTransport("smtp"); try { trans.connect(smtpHost, MailAuthenticator.FEIXIN_MAIL_USER, MailAuthenticator.FEIXIN_MAIL_PASSWORD);//, HUAWEI_MAIL_PASSWORD); } catch (AuthenticationFailedException e) { e.printStackTrace(); System.out.println("连接邮件服务器错误:"); return 3; } catch (MessagingException e) { System.out.println("连接邮件服务器错误:"); return 3; } trans.send(msg); trans.close();
} catch (MessagingException mex) { System.out.println("发送邮件失败:"); mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { System.out.println(ex.toString()); ex.printStackTrace(); } return 3; } finally { try { if (trans != null && trans.isConnected()) trans.close(); } catch (Exception e) { System.out.println(e.toString()); } } System.out.println("发送邮件成功!"); return 0; } public void setAttachedFileList(java.util.Vector filelist) { attachedFileList = filelist; } public void setDebug(boolean debugFlag) { debug=debugFlag; } public void setMailAccount(String strAccount) { mailAccount = strAccount; } public void setMailbccTo(String bccto) { mailbccTo = bccto; } public void setMailccTo(String ccto) { mailccTo = ccto; } public void setMailFrom(String from) { mailFrom=from; } public void setMailPass(String strMailPass) { mailPass = strMailPass; } public void setMailTo(String to) { mailTo=to; } public void setMessageBasePath(String basePath) { messageBasePath=basePath; } public void setMessageContentMimeType(String mimeType) { messageContentMimeType = mimeType; } public void setMsgContent(String content) { msgContent=content; } public void setSMTPHost(String host) { smtpHost=host; } public void setSubject(String sub) { subject=sub; }// public static void main(String[] argv) throws Exception
//
// {
//
// MailSend sm = new MailSend();
//
// sm.setSMTPHost("smtp.163.com");
//
// sm.setMailFrom("[email protected]");
//
// sm.setMailTo("[email protected]");
//
// sm.setMsgContent("sss");
//
// sm.setSubject("标题");
//
// sm.sendMail();
//
//
//
// }}
class MailAuthenticator extends Authenticator{ //****************************** //由于发送邮件的地方比较多, //下面统一定义用户名,口令. //****************************** public static String FEIXIN_MAIL_USER = "[email protected]"; public static String FEIXIN_MAIL_PASSWORD = "xxxx"; public MailAuthenticator() { } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(FEIXIN_MAIL_USER, FEIXIN_MAIL_PASSWORD); }}
注: 当时做一个意见回馈是在网上看到的,很好用的!已经测试完了.希望能帮到你.
发送人Mail地址:[email protected]
收件人Mail地址:[email protected]
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.163.com", port 25220 163.com Anti-spam GT for Coremail System (163com[20090903])
DEBUG SMTP: connected to host "smtp.163.com", port: 25EHLO
500 Error: bad syntax
HELO
500 Error: bad syntax
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 500 Error: bad syntax at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at mail.javaMail.sendMail(javaMail.java:55)
at mail.javaMail.main(javaMail.java:68)要不就是报 认证失败 530
不晓得怎么回事
我这里有一个QQ对QQ邮箱发的
package com.accp800.model;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.Message.RecipientType;
import javax.swing.JFileChooser;
public class SetEmail {
public void sendMail(String to, String from, String subject, String content) throws AddressException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session); //相当于一张白纸
msg.setFrom(new InternetAddress(from));
msg.addRecipient(RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport trans = session.getTransport("smtp");
trans.connect("smtp.qq.com", "自己的QQ", "密码");
trans.sendMessage(msg, msg.getAllRecipients());
trans.close();
}
public void sendMultipartMail(String from, String to) throws AddressException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session); //相当于一张白纸
msg.setFrom(new InternetAddress(from));
msg.addRecipient(RecipientType.TO, new InternetAddress(to));
msg.setSubject("带附件的邮件");
msg.setSentDate(new Date());
MimeMultipart parts = new MimeMultipart();
BodyPart htmlConent = new MimeBodyPart();
htmlConent.setContent("<a href=\"http://www.sina.com\">新浪</a>", "text/html;charset=gb2312");
parts.addBodyPart(htmlConent);
JFileChooser chooser = new JFileChooser(".");
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
if(file != null && file.exists()) {
DataSource source = new FileDataSource(file);
DataHandler handler = new DataHandler(source);
BodyPart attach = new MimeBodyPart();
attach.setDataHandler(handler);
attach.setFileName(file.getName());
parts.addBodyPart(attach);
}
msg.setContent(parts);
Transport trans = session.getTransport("smtp");
trans.connect("smtp.qq.com", "自己的QQ", "密码");
trans.sendMessage(msg, msg.getAllRecipients());
trans.close();
}
public static void main(String[] args) {
try {
SetEmail mp = new SetEmail();
mp.sendMail("对方[email protected]", "自己[email protected]", "hello", "jlkfsdakjflasjdflasjdf");
//mp.sendMultipartMail("自己[email protected]", "对方[email protected]");
//mp.recieveMail();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我用你的代码 就报错了:
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:264)
at javax.mail.Service.connect(Service.java:134)
at s.SetEmail.sendMultipartMail(SetEmail.java:87)
at s.SetEmail.main(SetEmail.java:97)
不要用新申请的邮箱。那样不会有smtp协议的权限。
你可以用qq邮箱。smtp.qq.com
然后在你的qq邮箱开启pop/smtp的协议。我的这种说法不知道会不会解决你的问题。
你可以试一下。