一个读取Gmail邮件的简单程序

      兄弟我理论性的东西说不出来,不过实际运用咱还是有办法的
前几天由于工作需要,想了解下关于支持ssl的邮件收发,按照以前普通的做法是行不通的,所以就上网东找找,西瞧瞧。发现了个好东西,并且实验成功。
      那天本想来javaeye看看有没有人有相关的经验,找了老半天,连个屁也没闻到,我就说我们,我们这些做程序员的不能老是吹吹水,谈谈道理,我们得拿出点实际的东西出来,就想fins一样,我就很佩服他的贡献精神。
      不说废话了,看看源代码,大家有空也可以实验下。还真有用
java 代码
 
  1. /** 
  2.  * 用于收取Gmail邮件 
  3.  *  
  4.  * @author wuhua 
  5.  */  
  6. public class GmailFetch {  
  7.     private static Logger logger = Logger.getLogger(GmailFetch.class);  
  8.     public static void main(String argv[]) throws Exception {  
  9.         logger.debug("开始读取邮件......");  
  10.         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());  
  11.         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";  
  12.   
  13.         // Get a Properties object  
  14.         Properties props = System.getProperties();  
  15.         props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);  
  16.         props.setProperty("mail.pop3.socketFactory.fallback""false");  
  17.         props.setProperty("mail.pop3.port""995");  
  18.         props.setProperty("mail.pop3.socketFactory.port""995");  
  19.   
  20.         // 以下步骤跟一般的JavaMail操作相同  
  21.         Session session = Session.getDefaultInstance(props, null);  
  22.   
  23.         // 请将红色部分对应替换成你的邮箱帐号和密码  
  24.         URLName urln = new URLName("pop3", ApplicationContext.POP3, 995null,  
  25.                 ApplicationContext.GMAIL_MAIL_NAME, //这里替换您的gmail用户名 
  26.                 ApplicationContext.GMAIL_MAIL_PASSWORD);  //这里替换密码
  27.         Store store = session.getStore(urln);  
  28.         Folder inbox = null;  
  29.         try {  
  30.             store.connect();  
  31.             inbox = store.getFolder("INBOX");  
  32.             inbox.open(Folder.READ_ONLY);  
  33.             FetchProfile profile = new FetchProfile();  
  34.             profile.add(FetchProfile.Item.ENVELOPE);  
  35.             Message[] messages = inbox.getMessages();  
  36.             inbox.fetch(messages, profile);  
  37.             logger.debug("收件箱的邮件数:" + messages.length);  
  38.             for (int i = 0; i < messages.length; i++) {  
  39.                 // 邮件发送者  
  40.                 String from = decodeText(messages[i].getFrom()[0].toString());  
  41.                 InternetAddress ia = new InternetAddress(from);  
  42.                 logger.debug("发信人:" + ia.getPersonal() + '('  
  43.                         + ia.getAddress() + ')');  
  44.                 // 邮件标题  
  45.                 logger.debug("主题:" + messages[i].getSubject());  
  46.                 // 邮件大小  
  47.                 logger.debug("邮件大小:" + messages[i].getSize());  
  48.                 // 邮件发送时间  
  49.                 logger.debug("发送日期:" + messages[i].getSentDate());  
  50.             }  
  51.         } finally {  
  52.             try {  
  53.                 inbox.close(false);  
  54.             } catch (Exception e) {  
  55.             }  
  56.             try {  
  57.                 store.close();  
  58.             } catch (Exception e) {  
  59.             }  
  60.         }  
  61.           
  62.         logger.debug("读取邮件完毕......");  
  63.     }  
  64.   
  65.     protected static String decodeText(String text)  
  66.             throws UnsupportedEncodingException {  
  67.         if (text == null)  
  68.             return null;  
  69.         if (text.startsWith("=?GB") || text.startsWith("=?gb"))  
  70.             text = MimeUtility.decodeText(text);  
  71.         else  
  72.             text = new String(text.getBytes("ISO8859_1"));  
  73.         return text;  
  74.     }  
  75.   
  76. }  
上面代码,完全可以封装成一个收取ssl邮件的库
改天有时间整理下关于发邮件的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,我是一名语言模型,无法编写和执行代码。但我可以提供一些思路和建议: 要发送图片,可以使用邮件协议中的附件功能。具体步骤如下: 1. 打开要发送的图片文件,读取图片内容; 2. 将图片内容编码为base64格式,以便在邮件中传输; 3. 使用SMTP协议发送邮件,设置邮件主题、发件人、收件人、内容类型等参数; 4. 将图片内容作为附件添加到邮件中,设置附件名称和类型; 5. 发送邮件。 以下是一个示例代码,仅供参考: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #define SMTP_SERVER "smtp.gmail.com" #define SMTP_PORT 587 #define SMTP_USER "your_username@gmail.com" #define SMTP_PASS "your_password" #define FROM_ADDR "your_username@gmail.com" #define TO_ADDR "recipient@example.com" #define SUBJECT "Test Email with Attachment" #define IMG_FILE "test.jpg" #define IMG_NAME "test.jpg" #define IMG_TYPE "image/jpeg" int main() { CURL *curl; CURLcode res; struct curl_slist *recipients = NULL; struct curl_slist *headers = NULL; char payload[4096]; char encoded_img[4096]; FILE *fp; long img_size; size_t result; // read image file fp = fopen(IMG_FILE, "rb"); if (fp == NULL) { printf("Failed to open file!\n"); return 1; } fseek(fp, 0, SEEK_END); img_size = ftell(fp); rewind(fp); char *img_data = (char *) malloc(img_size + 1); result = fread(img_data, 1, img_size, fp); if (result != img_size) { printf("Failed to read file!\n"); fclose(fp); return 1; } fclose(fp); // encode image in base64 CURL *enc = curl_easy_init(); CURLcode enc_res; enc_res = curl_easy_escape(enc, img_data, img_size); if (enc_res != CURLE_OK) { printf("Failed to encode image!\n"); return 1; } strcpy(encoded_img, enc->out_buf); curl_easy_cleanup(enc); // create email payload sprintf(payload, "From: %s\r\n", FROM_ADDR); sprintf(payload + strlen(payload), "To: %s\r\n", TO_ADDR); sprintf(payload + strlen(payload), "Subject: %s\r\n", SUBJECT); sprintf(payload + strlen(payload), "MIME-Version: 1.0\r\n"); sprintf(payload + strlen(payload), "Content-Type: multipart/mixed; boundary=boundary1\r\n\r\n"); sprintf(payload + strlen(payload), "--boundary1\r\n"); sprintf(payload + strlen(payload), "Content-Type: text/plain\r\n\r\n"); sprintf(payload + strlen(payload), "This is a test email with attachment.\r\n\r\n"); sprintf(payload + strlen(payload), "--boundary1\r\n"); sprintf(payload + strlen(payload), "Content-Type: %s; name=%s\r\n", IMG_TYPE, IMG_NAME); sprintf(payload + strlen(payload), "Content-Disposition: attachment; filename=%s\r\n", IMG_NAME); sprintf(payload + strlen(payload), "Content-Transfer-Encoding: base64\r\n\r\n"); sprintf(payload + strlen(payload), "%s\r\n\r\n", encoded_img); sprintf(payload + strlen(payload), "--boundary1--\r\n"); // initialize curl curl = curl_easy_init(); if (curl) { // set smtp server and port curl_easy_setopt(curl, CURLOPT_URL, SMTP_SERVER); curl_easy_setopt(curl, CURLOPT_PORT, SMTP_PORT); // set user authentication curl_easy_setopt(curl, CURLOPT_USERNAME, SMTP_USER); curl_easy_setopt(curl, CURLOPT_PASSWORD, SMTP_PASS); // set email parameters curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_ADDR); recipients = curl_slist_append(recipients, TO_ADDR); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); headers = curl_slist_append(headers, "Content-Type: text/plain"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // set email payload curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_READDATA, NULL); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_READDATA, payload); curl_easy_setopt(curl, CURLOPT_INFILESIZE, (long) strlen(payload)); // send email res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("Failed to send email: %s\n", curl_easy_strerror(res)); } // cleanup curl_slist_free_all(recipients); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return 0; } ``` 需要注意的是,该示例代码使用了libcurl库来发送SMTP邮件,并以Gmail为例。如果使用其他邮箱服务,请根据实际情况修改SMTP服务器地址、端口、用户名、密码等参数。同时,也需要确认libcurl库是否已经正确安装并链接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值