You can access gmail using your username and password. But gmail access will be denied.
Thus, you need to change the security level by going to the account settings, the password section and unzip the security settings of the verification code or lower the security level, depending on the old or latest gmail application.
If you want to send the attachment via gmail, referring to the local directory, you need to use the File object, which must be installed in the DataSource constructor class, as indicated in the program below. This will eliminate the "Access Denied" exception.
import java.io.File; import java.io.IOException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class EmailApp { public static void main(String[] args)throws IOException { final String username = " mygmail@gmail.com "; final String password = "mypassword"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(" dharmendrasundar@gmail.com ")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(" dharmendrasundar@gmail.com ")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); message.setSubject("Testing Subject"); message.setText("PFA"); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); String attachmentPath = "C:/TLS/logs/26-Mar-2015"; String attachmentName = "LogResults.txt"; File att = new File(new File(attachmentPath), attachmentName); messageBodyPart.attachFile(att); DataSource source = new FileDataSource(att); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachmentName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); System.out.println("Sending"); Transport.send(message); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
source share