簡單的程序是這樣的
package doudou;
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
/**
* @author Bromon
*/
public class SenderWithSMTPVer
{
String host="";
String user="";
String password="";
public void setHost(String host)
{
this.host=host;
}
public void setAccount(String user,String password)
{
this.user=user;
this.password=password;
}
public void send(String from,String to,String subject,String content)
{
Properties props = new Properties();
props.put("mail.smtp.host", host);//指定SMTP服務器
props.put("mail.smtp.auth", "true");//指定是否需要SMTP驗證
try
{
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制臺顯示debug信息
Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//發件人
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人
message.setSubject(subject);//郵件主題
message.setText(content);//郵件內容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
SenderWithSMTPVer sm=new SenderWithSMTPVer();
sm.setHost("smtp.tom.com");//指定要使用的郵件服務器
sm.setAccount("morningq","******");//指定帳號和密碼
/*
* @param String 發件人的地址
* @param String 收件人地址
* @param String 郵件標題
* @param String 郵件正文
*/
sm.send("morningq@tom.com","zeng@tom.com","標題","內容");
}
}
編譯通過了,但始終無法得到服務器的響應
我仿佛記得用這中方式進行收發郵件必須要你所使用的郵件服務商提供pop和smtp服務。對嗎?