PHP、Java和C++都可以与IMAP服务器结合使用,实现邮件的发送和接收功能,下面分别介绍这三种语言的实现方法:
1. PHP:
<?php $hostname = '{imap.gmail.com:993/imap/ssl/oauth2}INBOX;'; $username = 'your_email@example.com'; $password = 'your_password'; $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error()); $emails = imap_search($inbox, 'UNSEEN'); $unread_count = count($emails); imap_close($inbox); echo "Unread emails count: " . $unread_count; ?>
2. Java:
import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) { String to = "recipient@example.com"; String from = "your_email@example.com"; String host = "smtp.gmail.com"; String username = "your_email@example.com"; String password = "your_password"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.port", "587"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); 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 sent using JavaMail API and IMAP."); Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Email sent successfully!"); } catch (MessagingException e) { e.printStackTrace(); } } }
3. C++:
还没有评论,来说两句吧...