試試這個代碼...
public class SendAttachment{
public static void main(String [] args){
//to address
String to="[email protected]";//change accordingly
//from address
final String user="[email protected]";//change accordingly
final String password="password";//change accordingly
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
//1) get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hii");
//3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("How is This");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
//Location of file to be attached
String filename = Environment.getExternalStorageDirectory().getPath()+"/R2832.zip";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName("Hello");
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart);
//7) send message
Transport.send(message);
System.out.println("MESSAGE SENT....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
我已經搜索了這個很長一段時間。雖然這樣做似乎很合乎邏輯,但實際上沒有辦法。事實上,你所能做的就是發送一封電子郵件,意圖讓用戶自己發送電子郵件,或者輸入自己的憑證,即使你不想。 – Alpay 2013-02-27 08:17:53
爲了保護用戶,您可能會認爲Google會提供一個簡單的API,如果用戶授予應用權限,則讓該應用使用帳戶設置發送電子郵件,而無需訪問用戶的用戶名和密碼。 – AndroidDev 2013-02-27 08:20:38
@ChintanRathod在允許的情況下,應該可以在沒有用戶交互的情況下發送電子郵件。這樣思考並不荒謬。然而,有一種方法可以做到這一點,但我不知道。我無法實現這一點,並分享我的經驗。 – Alpay 2013-02-27 08:44:43