Mail.java:18: error: cannot find symbol - java

import java.security.Security;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public String to;
public String subject;
public String text;
SendMail(String to, String subject, String text){
this.to = to;
this.subject = subject;
this.text = text;
}
public void send() throws NoSuchProviderException, AddressException{
try
{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props=new Properties();
props.setProperty("mail.transport.protocol","smtp");
props.setProperty("mail.host","mail.epro-tech.com");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
props.put("mail.debug","true");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
Session session=Session.getDefaultInstance(props,new GJMailAuthenticator());
session.setDebug(true);
Transport transport=session.getTransport();
InternetAddress addressFrom=new InternetAddress("itopstest#epro-tech.com");
MimeMessage message=new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(text,"text/html");
InternetAddress addressTo=new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO,addressTo);
transport.connect();
Transport.send(message);
transport.close();
System.out.println("DONE");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class GJMailAuthenticator extends javax.mail.Authenticator{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("itopstest#epro-tech.com","Ops#890T");
}
}
public class Mail extends SendMail {
public static void main(String[] args) {
String to = "noreply#eprocorp.com";
String subject = "Test";
String message = "A test message";
SendMail SendMail = new SendMail(to, subject, message);
try
{
SendMail.send();
}
catch (Exception e)
{
//
}
}
}
receiving the error
Mail.java:18: error: cannot find symbol
SendMail SendMail = new SendMail(to, subject, message);
^
symbol: class SendMail
location: class Mail
Mail.java:18: error: cannot find symbol
SendMail SendMail = new SendMail(to, subject, message);
^
symbol: class SendMail
location: class Mail
2 errors
can any one plz suggest me how to rectify this

I can see there are problems.
Mail class is extending SendMail class which do not have default cunstructor. so either create a default cunstructor in SendMail class or create a parameterize cunstructor in Mail class
SendMail.send(); here i guess compiler is trying to access static method of SendMail class. create your object like SendMail sendMail = new SendMail(to, subject, message); and access send method like sendMail.send();
Give proper package name to both your classes because your class has common names which may be found in jars.

code already containd a constructor
SendMail(String to, String subject, String text)
{
this.to = to;
this.subject = subject;
this.text = text;
}
even at extends in the class Mail i can see the errors

Related

How to use libraries correctly in Netbeans (Java)?

This question is about how to handle libraries in Netbeans, when programming in Java.
I am having a Java project, let's call it ABC. One of its activities is to send an email message. Some of my other Java projects also send email messages, so I decided to create a separate Java project for sending messages. This project is called SendEmail. SendEmail uses external jar files (javax.mail.*). These are included by going to SendEmail's project Properties -> Libraries -> Add JAR. Testing SendEmail works fine: when calling its method sendMail(title, contents) do I receive the email which is sent.
Project ABC uses SendEmail, so I have added this to ABC's library: project Properties -> Libraries -> Add Project. ABC compiles and runs fine until it reaches the point where it wants to send an email: it crashes.
private void informUser(){
//create message title
//create message contents
SendEmail email = new SendEmail();
email.sendMail(title, contents); // <- it crashes here
}
The error information states that it can't find the Authenticator class. This class is in the external jar file which is included in SendEmail's library.
I can only avoid this crash from happening by including the external jar files to ABC's library. This is what I did not expect to be necessary. ABC does not use these external jar files, only SendEmail does.
My question: am I doing something wrong? I assumed that ABC is not using these external jar's so they don't need to be in ABC's library.
In your code don`t have the authenticator part. This code only can use gmail email, you can change smtp server options. My code:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GmailSender extends javax.mail.Authenticator {
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public GmailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
And do you need this class:
import java.security.AccessController;
import java.security.Provider;
public class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
For used this code:
class SendEmailTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
GmailSender sender = new GmailSender("from email", "from email password");
//subject, body, sender, to
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
sender.sendMail("your title",
"your content",
"from email",
"to email");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
and run
SendEmailTask sendEmailTask = new SendEmailTask();
sendEmailTask.execute();
UPD1:
Libs:
1. javax.activation
2. javax.mail

javamail isnt sending mail by gmail?

im trying to develop an android mailbox app which would send and receive emails.
but im having issue by sending mail on javamail.
here is the codes;
ComposeMail.Java
package app.mailbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.util.Log;
public class Composemail extends AppCompatActivity {
private String to;
private String subject;
private String message;
private String username;
private String password;
public void sendthemail(View view) {
EditText toarea, subjectarea,messagearea;;
toarea = (EditText) findViewById(R.id.et_to);
subjectarea = (EditText) findViewById(R.id.et_sub);
messagearea = (EditText) findViewById(R.id.et_text);
String to = toarea.getText().toString();
String subject = subjectarea.getText().toString();
String message = messagearea.getText().toString();
try {
GMailSender sender = new GMailSender(username, password);
sender.sendMail(subject, message, username, to);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_composemail);
username = Login.username;
password = Login.password;
}
}
GmailSender.java
package app.mailbox;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new app.mailbox.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
JSSE Provider
package app.mailbox;
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
im new to android development guys, i have no idea about why it isnt running, i also tryed debugging too but didnt find out anything.
https://www.tutorialspoint.com/javamail_api/javamail_api_gmail_smtp_server.htm
also can i use this tutorial for android javamail app? or its not for android?
and i need a solution about how i can add a google autherization i mean a checking system which will check if given email and password is exist as gmail account? and i want to do that at login screen?

Java Send Email Illegal semicolon?

I'm trying to send emails with java from database. After I run my main method for some reason I'm getting this error:
Exception in thread "main" javax.mail.internet.AddressException: Illegal semicolon, not in group in string ``john#gmail.com;eric#gmail.com;carrie#gmail.com;mark#gmail.com;britney#gmail.com'' at position 23
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:929)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:638)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:615)
at EmailSender.sendEmail(TestSendEmails.java:120)
at EmailSender.sendEmail(TestSendEmails.java:128)
at Main.main(Main.java:8)
I'm assuming that my array list is built wrong. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestSendEmails {
private String emailTo;
private String emailSubject;
private String emailBody;
private String emailAttachments;
public TestSendEmails(){
}
public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments){
super();
this.emailTo = emailTo;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.emailAttachments = emailAttachments;
}
public String getEmailTo(){
return emailTo;
}
public void setEmailTo(String emailTo){
this.emailTo = emailTo;
}
public String getEmailSubject(){
return emailSubject;
}
public void setEmailSubject(String emailSubject){
this.emailSubject = emailSubject;
}
public String getEmailBody(){
return emailBody;
}
public void setEmailBody(String emailBody){
this.emailBody = emailBody;
}
public String getEmailAttachments(){
return emailAttachments;
}
public void setEmailAttachments(String emailAttachments){
this.emailAttachments = emailAttachments;
}
}
class TestSendEmailD{
private Connection con;
private static final String GET_EMAILS = "Select * From Emails";
private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://100.000.000.00\\SQLEXPRESS:3333;databaseName=dEmails;user=sys;password=admin");
}
public List<TestSendEmails> getTestSendEmails() throws Exception{
connect();
PreparedStatement ps = con.prepareStatement(GET_EMAILS);
ResultSet rs = ps.executeQuery();
List<TestSendEmails> result = new ArrayList<TestSendEmails>();
while(rs.next()){
result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments")));
}
disconnect();
return result;
}
private void disconnect() throws SQLException{
if(con != null){
con.close();
}
}
}
class EmailSender{
private Session session;
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.000.000.00");
props.put("mail.smtp.port", "123");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("work#gmail.comg", "1234");
}
});
}
public void sendEmail(TestSendEmails s) throws MessagingException{
init();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("work#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo()));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
Transport.send(message);
}
public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
for(TestSendEmails TestSendEmails:emails ){
sendEmail(TestSendEmails);
}
}
}
here is my main.java:
public class Main {
public static void main(String[] args) throws Exception {
TestSendEmailD dao=new TestSendEmailD();
List<TestSendEmails> list=dao.getTestSendEmails();
EmailSender sender=new EmailSender();
sender.sendEmail(list);
}
}
Can anyone help with this? Thanks in advance.
By default it parse with comma(,) separated email addresses and not with semicolon (;),
InternetAddress[] parse = InternetAddress.parse("abc#gmail.com,pqr#gmail.com");
System.out.println(parse[0].getAddress());
OUTPUT:
abc#gmail.com

JAVA Problems sending email in HTML format with embedded image

Hello guys i lost two hours to solve this problem.
I have a Java class that send mail and the body inside is in HTML format
here that method
private void sendMail() {
String body = "<html><body><p>Mr.<b>Jack Frusciante</b><br/>Work : <b>Programmer</b><br/><img alt=\"Firm\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAA7VBMVEX///90yW8IZGXp9uYAWlsAYWJRg4SNqqoAXl9wyGuzzs72/PVyo6QAU1QddHUAWVrs8vJtx2ef2Zz5/fkSbW7t+Oub2JjZ5+doxWKGz4J7zHYAYWXH2dnh7OyN0olBgoJbrXrc8duCzn0ATU+lxMTQ7M7A5b+T1I+n3KSy4K+UubrW7tUudHWbuLiBrq7J6MZPiJBpmpqv2rRXlZZHjI3B0NC14LNjnZx+pqe309I6eHlXrnE+h4iHyo+qy8ZxtJCUwLJmsYRGm2sbc2ZrwG5Spmw3jGh/rpw3eH+by6gAa2IxhmgCZXEAWGRgtW0uQDJmAAAF9ElEQVR4nO2Ya3uiZhCGESHhIAICi6JoZDHGeCrVZNVs0+22Tdttu///53RmOKhRs1F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Crv8BpYb+vmjKrcVI9PAmNFVJJThq8Qy+aHH7HVeDutBluL2te77Y1NhNpNPt/YbzA0xhLEx6XBl1RMILRKd5WQBEICxfgEfbAYY0muWr0IFXjPBF6XyAbODRp9uo6V+m8ysMtYSZ4ddMZ7Egh65IvsKga0oJYEz3Dq25gMAoUbGLeez4ICtrr6MPVF2lDSWMODOdshUGA168lYL6lZBMiakqwFytB/Xt0Dd3ivgMB7GwQ62wI98gNEplSERSzVSu8CeBCCAlq+dXP2MWu5IPy6aD+n8E4CgT0S6G1P0w0qQdg7sE2n+3C5rWarXQuigErwFpZvRCUo5c35FltLNjUI1MxE5bQKTK8GAofkgm2BQzUbZbyocAkJxMobwoZSp40OZkoSGGICU6dWcEzKL1OlHbpz+vtTbILAbrQrEEeZdF5pq/kRClSjwXSABo/obMrQXGthx8qcig37/ZbAMxIoWAYILLdRoL71QofmjWjkwyO1RtEBTTI2DQzYpQXHoBWUTLkwBg4PacNGcIOWL0LhZCwRBHr9XYENENKnCeLahqbXpiimkLCjdBjU0LGTEb4iSZ1UhiYqslFM0/RaMX5JQXz5IgvXjTXtp4dHTXt8hD85j1fAzxT4gIe/pN99uHqwgWiQdW7oyaIpLOem6S6ygT+ezWbrbQOWWF69VIHW3JBeRHF9y9Kt1zOc9rzilwasNxijrDC08pCDJxW3hweQXnx7shYXX2B2usNoml7X2+7NcZI4oweezxIHhLsDX44nCXpcPuZN5P+GpukDFg1HEhpEPpzgr8ClcrgJLyF9siwtvq6ibXAQlQ8NepjdUedbri+YQBvH40M/ILTGcXzujwsMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAM8z3xHzxMgUvIvKzHAAAAAElFTkSuQmCC\"/><br/><p>Lorem ipsum</p></p></body></html>";
SendMail sendMail = new SendMail("jack#gmail.com","othermail#gmail.com","subject","");
sendMail.setCC("othermailcc#gmail.com");
sendMail.setBody(body);
sendMail.send();
}
and here the SendMail class
package com.jack.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.mail.BodyPart;
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;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.PreencodedMimeBodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.mail.SMTPAccount;
import com.liferay.util.mail.MailEngine;
import com.sun.mail.smtp.SMTPMessage;
public class SendMail {
private String from;
private String subject;
private String body;
private String to;
private String cc;
private String cid;
private String smtpHost;
private String smtpPort;
private Boolean authenticationRequired;
private String authenticationUsername;
private String authenticationPassword;
public SendMail(String from,String to,String subject,String body) {
super();
this.to = to;
this.from = from;
this.subject = subject;
this.body = body;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpPort() {
return smtpPort;
}
public void setSmtpPort(String smtpPort) {
this.smtpPort = smtpPort;
}
public Boolean getAuthenticationRequired() {
return authenticationRequired;
}
public void setAuthenticationRequired(Boolean authenticationRequired) {
this.authenticationRequired = authenticationRequired;
}
public String getAuthenticationUsername() {
return authenticationUsername;
}
public void setAuthenticationUsername(String authenticationUsername) {
this.authenticationUsername = authenticationUsername;
}
public String getAuthenticationPassword() {
return authenticationPassword;
}
public void setAuthenticationPassword(String authenticationPassword) {
this.authenticationPassword = authenticationPassword;
}
public void setCC(String cc) {
this.cc=cc;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public void send() {
new Thread( new Runnable() {
#Override
public synchronized void run() {
performSend();
}
}).start();
}
private void performSend() {
try {
Session session = getSession();
SMTPMessage transport = new SMTPMessage(session);
InternetAddress iaFrom = new InternetAddress(from, from);
InternetAddress iaTo = new InternetAddress(to,to);
InternetAddress iaCC = (cc!=null) ? new InternetAddress(cc,cc) : null;
MimeMultipart mailMessage = new MimeMultipart("related");
BodyPart bp = new MimeBodyPart();
bp.setContent(body,"text/html");
mailMessage.addBodyPart(bp);
transport.setContent(mailMessage);
transport.setFrom(iaFrom);
if(iaCC!=null) {
transport.setRecipient(RecipientType.CC, iaCC);
}
transport.setSubject(subject);
InternetAddress[] recipients = { iaTo };
Transport.send(transport, recipients);
System.out.println("Sent message successfully....");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Session getSession() {
Properties mailProps = new Properties();
mailProps.put("mail.transport.protocol", "smtp");
mailProps.put("mail.smtp.host", "smtp.gmail.com");
mailProps.put("mail.smtp.socketFactory.port", "465");
mailProps.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
mailProps.put("mail.smtp.auth", "true" );
mailProps.put("mail.smtp.port","465");
return Session.getInstance(mailProps,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("jack","jackpassword");
}
});
}
}
the mail arrives but image at the of html is never showed . I noted , inspected the source of message, that img tag is changed like this
<img alt=3D"Firm" src=3D"data:image/png;base64,iVBORw0KGgoAAAA=
NSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAA7VBMVEX///90yW8IZGXp9u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HqwgWiQdW7oyaIpLOem6S6ygT+ezWbrbQOWWF=
69VIHW3JBeRHF9y9Kt1zOc9rzilwasNxijrDC08pCDJxW3hweQXnx7shYXX2B2usNoml7X2+7Nc=
ZI4oweezxIHhLsDX44nCXpcPuZN5P+GpukDFg1HEhpEPpzgr8ClcrgJLyF9siwtvq6ibXAQlQ8N=
epjdUedbri+YQBvH40M/ILTGcXzujwsMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAM8z3xHzx=
MgUvIvKzHAAAAAElFTkSuQmCC"/>
and the body part starts with
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Anybody have an idea to solve this?
Thanks in advance
I think there was some problem similar to "twice encoding"... or something like.
You should try to understand how body message is transformed, inside the steps of sending process.
A smart alternative, if the image is in your document library and it is pubblic accessible, is to provide the URL instead the full-image content inside your email body... this may help you to avoid several potential issues related to SMTP protocol and mail server loading.
As an alternative, I suggest you to save your image in an image server and include its reference in the message body. Of course this solution will work as long as the image is available in the specific server that you use.
As and example, I uploaded your image to Imgur server and here is a simpler version to send mail from java:
package stack;
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 emailAddress){
String host = "smtp.gmail.com";
String from = "yourMail#gmail.com";
String subject = "Testing java mail";
String contentBody = "<html>\n" + "<body>\n"
+ "<p>Mr.<b>Jack Frusciante</b>\n"
+ "<br/>Work : <b>Programmer</b><br/>\n"
+ "<img src =\"http://imgur.com/81h91BL.png\"/>\n" + "<br/>\n"
+ "<p>Lorem ipsum</p></p>\n" + "</body>\n" + "</html>";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
try{
Session session = Session.getDefaultInstance(props, null);
InternetAddress to_address = new InternetAddress(emailAddress.toLowerCase());
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, to_address);
message.setSubject(subject);
message.setContent(contentBody, "text/html; charset=UTF-8");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "yourMail#gmail.com", "yourPassword");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("This notification was sent to : " + emailAddress +"");
}
catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}

How can I create run time entry for email and password in following code?

Following is the code of Main.java file.
package com.app.mail1;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
EditText to, from, message, subject;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
GMailSender sender = new GMailSender("rockstarjamunjuice#gmail.com", "jamunjuice");
sender.sendMail("This is Subject",
"This is Body",
"user#gmail.com",
"user#yahoo.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
Here is the code for GMailSender.java file
package com.app.mail1;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
Can I set the username and password at run time?
Can I make String to Editable?
Please help me if I can edit this code and set sender's email id and password at run time?
Howto convert String to Editable
Howto change username/password:
Add this to class:
public class Main extends Activity {
private static String password;
private static String username;
public static void setUsername(String user){
username = user;
}
public static void setPassword(String pass){
password = pass;
}
// ...................................
GMailSender sender = new GMailSender(username, password);
}
Then, you can change pass/name:
public class SomeClass {
Main.setUsername("SomeUser");
Main.setPassword("StrongPassword");
}
Or you can use Intent for transfer data (username/password) in Activity

Categories

Resources