JavaMail autenticação

Existe a possibilidade e eu autenticar com um email senha e smtp, e mandar com outro e-mail?

o setfrom só aceita o e-mail que eu autentico, eu queria enviar do meu proprio e-mail para que eu pudesse fazer um e-mail marketing mesmo sem saber o smtp login e senha dos meus clientes.
Tem como?

tem sim, normal. eu uso essa classe.


**
 * class that encapsulates the sending of messages through the javax.mail.
 *
 * @author Mauricio Lima
 * @date 18/07/2011
 */
public class SendMail {
	private Session session;
	private String user;

	public SendMail(boolean requiresAuthentication,
			boolean requiresSSLConection, String host, String port,
			final String user, final String password) {
		super();
		this.user = user;
		Properties props = new Properties();
		props.put("mail.smtp.auth", requiresAuthentication + "");
		props.put("mail.smtp.port", port);
		props.put("mail.host", host);
		if (requiresSSLConection) {
			props.put("mail.smtp.socketFactory.class",
					"javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");
		}

		Authenticator authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(user, password);
			}
		};

		this.session = Session.getInstance(props, authenticator);
	}

	/**
	 * Sends a simple e-mail
	 * @param subject
	 * @param body
	 * @param recipientTO
	 * @throws MessagingException
	 */
	public void sendMail(String subject, String body, String recipientTO) throws MessagingException{
		sendMail(subject, body, new String[]{ recipientTO }, null, null, null, "text/plain");
	}
	
	/**
	 * Sends a complete e-mail
	 * @param subject
	 * @param body
	 * @param recipientsTO
	 * @param recipientsCC
	 * @param recipientsBCC
	 * @param attachments
	 * @param content
	 * @throws MessagingException
	 */
	public void sendMail(String subject, String body, String[] recipientsTO,
			String[] recipientsCC, String[] recipientsBCC, File[] attachments, String content)
			throws MessagingException {
		// mount e-mail
		MimeMessage message = new MimeMessage(session);
                // pode por o e-mail que vc quiser aqui q funciona
		message.setFrom(new InternetAddress(this.user));
		message.setSentDate(new Date());
		message.setSubject(subject);
		Multipart mp = new MimeMultipart();

		// mount body
		MimeBodyPart mbp1 = new MimeBodyPart();
		mbp1.setText(body);
		mp.addBodyPart(mbp1);

		// add attachments
		if (attachments != null && attachments.length > 0) {
			for (File file : attachments) {
				MimeBodyPart mime = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(file);
				mime.setDisposition(Part.ATTACHMENT);
				mime.setDataHandler(new DataHandler(fds));
				mime.setFileName(fds.getName());
				mp.addBodyPart(mime);
			}
		}

		// add addresses TO
		if (recipientsTO != null && recipientsTO.length > 0) {
			InternetAddress[] destinationAddressesTO = new InternetAddress[recipientsTO.length];
			for (int i = 0; i < destinationAddressesTO.length; i++) {
				destinationAddressesTO[i] = new InternetAddress();
				destinationAddressesTO[i].setAddress(recipientsTO[i]);
			}
			message.setRecipients(Message.RecipientType.TO,
					destinationAddressesTO);
		}
		
		// add addresses CC
		if (recipientsCC != null && recipientsCC.length > 0) {
			InternetAddress[] destinationAddressesCC = new InternetAddress[recipientsCC.length];
			for (int i = 0; i < destinationAddressesCC.length; i++) {
				destinationAddressesCC[i] = new InternetAddress();
				destinationAddressesCC[i].setAddress(recipientsCC[i]);
			}
			message.setRecipients(Message.RecipientType.CC,
					destinationAddressesCC);
		}
		
		// add addresses BCC
		if (recipientsBCC != null && recipientsBCC.length > 0) {
			InternetAddress[] destinationAddressesBCC = new InternetAddress[recipientsBCC.length];
			for (int i = 0; i < destinationAddressesBCC.length; i++) {
				destinationAddressesBCC[i] = new InternetAddress();
				destinationAddressesBCC[i].setAddress(recipientsBCC[i]);
			}
			message.setRecipients(Message.RecipientType.BCC,
					destinationAddressesBCC);
		}
		// add content and complete part
		message.setContent(mp, content);
		
		// send the message
		Transport.send(message);
	}
}

Message message = new MimeMessage(session); message.setFrom(new InternetAddress("teste@hotmail.com"));
Estranho kkkk

exception
Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 teste@hotmail.com: Sender address rejected: Access denied

at SendMailTLS.<init>(SendMailTLS.java:57)
at Inicio.main(Inicio.java:61)

Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 teste@hotmail.com: Sender address rejected: Access denied

at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1873)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Envio.Enviar(Envio.java:38)
at SendMailTLS.<init>(SendMailTLS.java:53)
... 1 more

Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 teste@hotmail.com: Sender address rejected: Access denied

at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1771)
... 6 more

Esse problema pode estar ocorrêndo por alguma restrição no servidor de e-mail quanto ao domínio do endereço de e-mail que está configurando, no caso hotmail.com, verifique se existe alguma regra para esse caso.

no mais, segue outro exemplo de envio de e-mail, agrupei tudo em um método só para facilitar o post, mas uma refatoração cai bem aí =D

public void enviaEmail(List<String> destinatarios) {
		final Properties props = new Properties();
		
		/*
		 * CONFIGURAÇÃO DO SERVIDOR DE EMAIL PARA CONEXÃO AO SERVIÇO
		 */
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "IP do servidor de email"); 
		props.setProperty("mail.smtp.port", "Porta em que o serviço de email está disponível");
		props.setProperty("mail.mime.charset", "utf-8");

		final Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("usuario_servidor", "senha_servidor");
			}
		};
		Session session = Session.getInstance(props, auth);

		final Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("remetente"));
		boolean first = true;
		final InternetAddress internetAddress = new InternetAddress();
		
		/*
		 * A PARTIR DE UMA LISTA DE ENDEREÇOS DE E-MAILS ADICIONA-SE OS DESTINATÁRIOS DA MENSAGEM  
		 */
		for (int cont = 0; cont < destinatarios.size(); cont++) {
			if (first) {
				internetAddress.setAddress((String) destinatarios.get(cont));
				msg.addRecipient(Message.RecipientType.TO, internetAddress);
				first = false;
			} else {
				internetAddress.setAddress((String) destinatarios.get(cont));
				msg.addRecipient(Message.RecipientType.CC, internetAddress);
			}
		}
		
		/*
		 * MONTA O CORPO DO E-MAIL
		 */
		msg.setSubject("Aqui o assunto da mensagem");
		final MimeBodyPart corpoDaMensagem = new MimeBodyPart();
		corpoDaMensagem.setContent("Aqui a o corpo da mensagem que será enviada", "aqui os tipos 'text/html' ou 'text/plain'");

		final Multipart mps = new MimeMultipart();

		mps.addBodyPart(corpoDaMensagem);
		msg.setContent(mps);
	}

é na kinghost, vou falar com o pessoal de lá pra ver se é este o problema. as vezes nao posso mandar um e-mail de la com um e-mail “que nao seja meu”

Outra coisa…notei pela exceção que está abrindo uma conexão com um protocolo TLS de segurança, certifique-se também se o servidor de e-mail suporta conexões desse tipo.
TLS, caso não saiba, é uma camada de segurança para envio de informações pela rede.
tente nas propriedades da conexão setar false para não iniciar a conexão com protocolo tls

No exemplo que enviei ficaria assim:

        /* 
         * CONFIGURAÇÃO DO SERVIDOR DE EMAIL PARA CONEXÃO AO SERVIÇO 
         */  
        props.setProperty("mail.transport.protocol", "smtp");  
        props.setProperty("mail.host", "IP do servidor de email");   
        props.setProperty("mail.smtp.port", "Porta em que o serviço de email está disponível");  
        props;setProperty("mail.smtp.starttls.enable", "false");
        props.setProperty("mail.mime.charset", "utf-8");  
Você poderia fazer assim:

public void enviaEmail(List<String> destinatarios) {  
	try{ 
    	    SimpleEmail email = new SimpleEmail();
            email.setHostName(Ip Host);
            for (int cont = 0; cont < destinatarios.size(); cont++) {  
            	email.addTo(email do destinatario, destinatario nome);
            }
            email.setFrom(remetente, remetente nome);
            email.setSubject(assunto);
            email.setMsg(msg);
            email.setAuthentication(email, senha);
            email.setSmtpPort(465);
            email.setSSL(true);
            email.setTLS(true);
            email.send();
    	}catch(EmailException e){
    		// tratamento
    	}
}

desculpe a ignorancia
mas isso aqui?

message.setFrom(enviar,"teste@hotmail.com");

nao funcionou

Verifique a propriedade TLS como citei, no último post.

se eu colocar TLS false ele da um erro de que não foi permitido por eu ter colocado false no TLS

vamos lá… parece que da problema mesmo na king host, mas oque eu fiquei curioso é…
no hotmail funciona!
porem… mesmo funcionando ele ainda manda pelo e-mail que eu autentiquei… mesmo trocando o setFrom ele ainda envia pelo e-mail autenticado. O.o