java接收邮件_Java实现邮件收发
时间: 2023-06-29 19:18:42 浏览: 202
Java实现邮件收发需要使用JavaMail API,以下是一个简单的示例代码:
1. 发送邮件
```
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
String to = "recipient@example.com";
String from = "sender@example.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Email");
message.setText("This is a test email.");
Transport transport = session.getTransport("smtp");
transport.connect(host, "sender@example.com", "password");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
```
2. 接收邮件
```
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class ReceiveMail {
public static void main(String[] args) {
String host = "imap.gmail.com";
String username = "recipient@example.com";
String password = "password";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
properties.setProperty("mail.imap.host", host);
properties.setProperty("mail.imap.port", "993");
properties.setProperty("mail.imap.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties);
try {
Store store = session.getStore("imaps");
store.connect(host, username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
System.out.println("Total messages: " + messages.length);
for (int i = 0; i < messages.length; i++) {
System.out.println("Subject: " + messages[i].getSubject());
System.out.println("From: " + messages[i].getFrom()[0]);
System.out.println("Text: " + messages[i].getContent().toString());
}
inbox.close(false);
store.close();
} catch (MessagingException mex) {
mex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
请注意,此示例中使用的是Gmail的SMTP和IMAP服务器。如果使用其他邮件服务提供商,则需要更改主机名和端口号。另外,发送邮件需要提供发件人的邮箱地址和密码,而接收邮件需要提供收件人的邮箱地址和密码。
阅读全文