Roundcube smtp ошибка 554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

mcnesium opened this issue

May 13, 2020

· 5 comments

Comments

@mcnesium

I am trying to run Roundcube Webmail 1.4.4 in a Docker environment (see here for Dockerfile etc.) with the identity-smtp plugin, which allows me to also send mail from multiple mail accounts (identities).

Problem: sending mails does only work for recipients whose domain name is also handled by the same SMTP-server that I am trying to send mail to. For any other recipient, the following error message appears:

SMTP Error (554): Failed to add recipient «mail@recipient.tld» (Refused. Sending to remote addresses (relaying) is not allowed.)

I am not sure whether that is a configuration error or a bug within one of the components. For the plugin I already asked here, but no response there. In another non-dockerized setup and Roundcube Webmail 1.3.10 this plugin is included and works very well. So either this is an issue with v1.4.x or a configuration error.

How can I fix this? Any help?


This is a copy of my post in the roundcube forum which sadly does not seem to be very frequented anymore.

@alecpl

Looks like a config issue. Enable smtp_debug to see more details.

@mcnesium



Copy link


Contributor


Author

Enable smtp_debug to see more details.

How and where do I do that?

So here is the SMTP_DEBUG output seen by adding $config['smtp_debug'] = true; to config.inc.php and then doing docker logs -f while trying to send. First for sending a mail to an account that uses the same SMTP (same domain):

smtp: <7cc5f104> Connecting to tls://schedar.uberspace.de:587...
smtp: <7cc5f104> Recv: 220 schedar.uberspace.de ESMTP
smtp: <7cc5f104> Send: EHLO webmail.mydomain.de
smtp: <7cc5f104> Recv: 250-schedar.uberspace.de
smtp: <7cc5f104> Recv: 250-STARTTLS
smtp: <7cc5f104> Recv: 250-PIPELINING
smtp: <7cc5f104> Recv: 250-8BITMIME
smtp: <7cc5f104> Recv: 250 AUTH LOGIN PLAIN
smtp: <7cc5f104> Send: MAIL FROM:<mail@mydomain.de>
smtp: <7cc5f104> Recv: 250 ok
smtp: <7cc5f104> Send: RCPT TO:<qwer@mydomain.de>
smtp: <7cc5f104> Recv: 250 ok
smtp: <7cc5f104> Send: DATA
smtp: <7cc5f104> Recv: 354 Proceed.
…

And here is the output when sending to some other address on a different mail server:

smtp: <7cc5f104> Connecting to tls://schedar.uberspace.de:587...
smtp: <7cc5f104> Recv: 220 schedar.uberspace.de ESMTP
smtp: <7cc5f104> Send: EHLO webmail.mydomain.de
smtp: <7cc5f104> Recv: 250-schedar.uberspace.de
smtp: <7cc5f104> Recv: 250-STARTTLS
smtp: <7cc5f104> Recv: 250-PIPELINING
smtp: <7cc5f104> Recv: 250-8BITMIME
smtp: <7cc5f104> Recv: 250 AUTH LOGIN PLAIN
smtp: <7cc5f104> Send: MAIL FROM:<mail@mydomain.de>
smtp: <7cc5f104> Recv: 250 ok
smtp: <7cc5f104> Send: RCPT TO:<mail@otherdomain.com>
smtp: <7cc5f104> Recv: 554 Refused. Sending to remote addresses (relaying) is not allowed.
errors: <7cc5f104> PHP Error: Invalid response code received from server (POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US&_action=send)
smtp: <7cc5f104> Send: RSET
smtp: <7cc5f104> Recv: 250 flushed
errors: <7cc5f104> SMTP Error: Failed to add recipient 'mail@otherdomain.com'. Refused. Sending to remote addresses (relaying) is not allowed. (Code: 554) in /var/www/html/program/lib/Roundcube/rcube.php on line 1702 (POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US&_action=send)
smtp: <7cc5f104> Send: QUIT
smtp: <7cc5f104> Recv: 221 schedar.uberspace.de172.21.0.1 - - [18/May/2020:13:40:31 +0000] "POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US HTTP/1.1" 200 956 "https://webmail.mydomain.de/?_task=mail&_action=compose&_id=15772262815ec29043a5049" "Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0"

Is that output more helpful?

@trasherdk

This is a server side configuration problem.
The mydomain.deis not recognized as a local domain, and not allowed to do stuff on that server.
Read the documentation for whatever server you are using. Look for relaying denied.

Long version of RTFM.

@mcnesium



Copy link


Contributor


Author

If this is really a configuration issue with the SMTP server, I wonder why it works with Roundcube v1.3.10 and below

@mcnesium



Copy link


Contributor


Author

I found out that it works, when commenting the encryption of passwords here and putting just $smtpSettings['smtp_pass']; instead of the decrypting here and then re-enter the passwords in the identity settings (passwords are then stored unencrypted to the database!) So there must be something wrong with the password en- or decryption.

I know this third party plugin is not actively maintained by Roundcube devs, but it seems to be abandoned, and so I am looking for help to be able to fix this myself.

Plus, I wonder how else we are supposed to make use of multiple identities feature in Roundcube, if we are not able to send mails through a separate SMTP server for each identity.

Who can help?

Topic: SMTP Error (554): Sending to remote addresses (relaying) is not allowed.  (Read 5166 times)

I am trying to run Roundcube Webmail 1.4.4 in a Docker environment (see here for Dockerfile etc.) with the identity-smtp plugin, which allows me to also send mail from multiple mail accounts (identities).

Problem: sending mails does only work for recipients whose domain name is also handled by the same SMTP-server that I am trying to send mail to. For any other recipient, the following error message appears:

> SMTP Error (554): Failed to add recipient «mail@recipient.tld» (Refused. Sending to remote addresses (relaying) is not allowed.)

I am not sure whether that is a configuration error or a bug within one of the components. For the plugin I already asked here, but no response there. In another non-dockerized setup and Roundcube Webmail 1.3.10 this plugin is included and works very well. So either this is an issue with v1.4.x or a configuration error.

How can I fix this? Any help?


Logged


Check the SMTP settings in your RC config, specifically smtp_user and smtp_pass. That error could me that you do not have SMTP auth enabled and you need it to send external mail.


Logged


Thank you for your reply. What exactly do you mean by «Check the SMTP settings»? Here is what they look like:

$ docker-compose exec roundcube cat config/config.inc.php
<?php
    $config
['db_dsnw'] = 'mysql://roundcube:xxxxxxxx@db:3306/roundcube';
    
$config['db_dsnr'] = '';
    
$config['default_host'] = 'ssl://imap.example.org';
    
$config['default_port'] = '993';
    
$config['des_key'] = 'xxxxxxxxxxxx';
    
$config['temp_dir'] = '/tmp/roundcube-temp';
    
$config['plugins'] = ['archive''zipdownload''enigma''jqueryui''managesieve''markasjunk''identity_smtp''carddav''contextmenu'];
    
$config['zipdownload_selection'] = true;
    
$config['log_driver'] = 'stdout';
    
$config['skin'] = 'elastic';
    
$config['smtp_server'] = 'xyz.uberspace.de';
    
$config['smtp_port'] = '587';
    
$config['smtp_user'] = 'abc@xyz.uberspace.de';
    
$config['smtp_pass'] = 'xxxxxxxx';

I added smtp_user and smtp_pass settings manually to the config file in the container, because they are not being added here (I might send a PR on that later) – then logged out and back in, all that.

But what is the matter with default SMTP settings anyway? Individual SMTP settings for each identity is exactly what the identity_smtp plugin is for, so the default SMTP settings of my RC should not matter at all, or is that a wrong assumption?


Logged


I added  $config[‘smtp_debug’] = true; to the config. The output doesn’t seem to include much better information about what is wrong:

Here is the output for sending a mail to an account that uses the same SMTP:

    smtp: <7cc5f104> Connecting to tls://schedar.uberspace.de:587…
    smtp: <7cc5f104> Recv: 220 schedar.uberspace.de ESMTP
    smtp: <7cc5f104> Send: EHLO webmail.mydomain.de
    smtp: <7cc5f104> Recv: 250-schedar.uberspace.de
    smtp: <7cc5f104> Recv: 250-STARTTLS
    smtp: <7cc5f104> Recv: 250-PIPELINING
    smtp: <7cc5f104> Recv: 250-8BITMIME
    smtp: <7cc5f104> Recv: 250 AUTH LOGIN PLAIN
    smtp: <7cc5f104> Send: MAIL FROM:<mail@mydomain.de>
    smtp: <7cc5f104> Recv: 250 ok
    smtp: <7cc5f104> Send: RCPT TO:<qwer@mydomain.de>
    smtp: <7cc5f104> Recv: 250 ok
    smtp: <7cc5f104> Send: DATA
    smtp: <7cc5f104> Recv: 354 Proceed.
    …

And here is the output when sending to some other receipient on a different mail server:

    smtp: <7cc5f104> Connecting to tls://schedar.uberspace.de:587…
    smtp: <7cc5f104> Recv: 220 schedar.uberspace.de ESMTP
    smtp: <7cc5f104> Send: EHLO webmail.mydomain.de
    smtp: <7cc5f104> Recv: 250-schedar.uberspace.de
    smtp: <7cc5f104> Recv: 250-STARTTLS
    smtp: <7cc5f104> Recv: 250-PIPELINING
    smtp: <7cc5f104> Recv: 250-8BITMIME
    smtp: <7cc5f104> Recv: 250 AUTH LOGIN PLAIN
    smtp: <7cc5f104> Send: MAIL FROM:<mail@mydomain.de>
    smtp: <7cc5f104> Recv: 250 ok
    smtp: <7cc5f104> Send: RCPT TO:<mail@otherdomain.com>
    smtp: <7cc5f104> Recv: 554 Refused. Sending to remote addresses (relaying) is not allowed.
    errors: <7cc5f104> PHP Error: Invalid response code received from server (POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US&_action=send)
    smtp: <7cc5f104> Send: RSET
    smtp: <7cc5f104> Recv: 250 flushed
    errors: <7cc5f104> SMTP Error: Failed to add recipient ‘mail@otherdomain.com’. Refused. Sending to remote addresses (relaying) is not allowed. (Code: 554) in /var/www/html/program/lib/Roundcube/rcube.php on line 1702 (POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US&_action=send)
    smtp: <7cc5f104> Send: QUIT
    smtp: <7cc5f104> Recv: 221 schedar.uberspace.de172.21.0.1 — — [18/May/2020:13:40:31 +0000] «POST /?_task=mail&_unlock=loading1589809230866&_framed=1&_lang=en_US HTTP/1.1» 200 956 «https://webmail.mydomain.de/?_task=mail&_action=compose&_id=15772262815ec29043a5049» «Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0»

Is that output more helpful?


Logged


I added smtp_user and smtp_pass settings manually to the config file in the container, because they are not being added here (I might send a PR on that later) – then logged out and back in, all that.

If you have a installation and you are using 1.4 then smtp auth is enabled by default so that is probably why they are not included in the config file.

But what is the matter with default SMTP settings anyway?

That is what we are trying to figure out isn’t it? You said it works fine with other clients right?

Individual SMTP settings for each identity is exactly what the identity_smtp plugin is for, so the default SMTP settings of my RC should not matter at all, or is that a wrong assumption?

I dont know anything about that plugin. If I were you I’d disable all plugins while trying to solve the issue in case it is being caused by one of them.


Logged


As I already wrote here, I was able to break down the problem to the encryption of the passwords.

Before storing the SMTP passwords to the database, they are being encrypted here:

            $password = rcmail::get_instance()->encrypt($password);
When sending a mail, the passwords are being decrypted here:

            $args['smtp_pass']   = rcmail::get_instance()->decrypt($smtpSettings['smtp_pass']);
I disabled both the encryption and decryption, and now the plugin works again, with the downside that the passwords are unencrypted in the database.

Do you have an idea how to fix the password encryption?

Also: sorry for late reply. I must have missed the reply notification.


Logged


I was facing same issue.That was explained well.

« Last Edit: August 17, 2020, 09:24:25 AM by GayuS »


Logged


I have been trying to setup a mail server on my ubuntu vServer for the last couple of days. I use postfix with mySQL and Courier. For webmail, I use roundcube.

I can receive emails to my address, but when I try to send an email using SMTP, I get the following error message: https://i.imgur.com/FxJByog.png
It doesn’t matter what address I send it to, I always get the same error. EDIT: I forgot to say that I can send mail to myself, only outbound mail doesn’t work.

Now after some googling, I found out this site: https://www.gammadyne.com/relaying_denied.htm which basically says that this error occurs when the user isn’t authenticating himself correctly. I am new to postfix and smpt, so I have not clue where to look for fixing this error.

This is the error message from /var/log/mail.log when I try to send a mail thorugh roundcube (cybershit.de is my domain, bnry.de is a second domain that links to the same IP, though cybershit.de is being used for the mail services):

NOQUEUE: reject: RCPT from vps1908220.fastwebserver.de[62.141.44.212]: 554 5.7.1 <example@example.com>: Relay access denied; from=<staddle@cybershit.de> to=<example@example.com> proto=ESMTP helo=<bnry.de> 

When I try to send a mail through Thunderbird, I get a SMTP error but nothing more specific.

I very much appreciate any help, I can post any other log files / config files if needed. Thank you!

Here are my config files:
postfix main.cf:

# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = cybershit.de ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no


# Uncomment the next line to generate "delayed mail" warnings

#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit 
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mail.cybershit.de
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = 
relayhost = 
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
#mynetworks = localhost
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

# Virtual Mailbox Domain Settings

virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_mailbox_limit = 51200000
virtual_minimum_uid = 5000
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_mailbox_base = /home/vmail
virtual_transport = virtual

# Additional for quota support

virtual_create_maildirsize = yes
virtual_mailbox_extended = yes
virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message = Sorry, the your maildir has overdrawn your diskspace quota, please free up some of spaces of your mailbox try again.
virtual_overquota_bounce = yes

Roundcubes config.inc.php:

<?php

/*
+-----------------------------------------------------------------------+
| Local configuration for the Roundcube Webmail installation.           |
|                                                                       |
| This is a sample configuration file only containing the minimum       |
| setup required for a functional installation. Copy more options       |
| from defaults.inc.php to this file to override the defaults.          |
|                                                                       |
| This file is part of the Roundcube Webmail client                     |
| Copyright (C) 2005-2013, The Roundcube Dev Team                       |
|                                                                       |
| Licensed under the GNU General Public License version 3 or            |
| any later version with exceptions for skins & plugins.                |
| See the README file for a full license statement.                     |
+-----------------------------------------------------------------------+
*/

$config = array();

/* Do not set db_dsnw here, use dpkg-reconfigure roundcube-core to configure database ! */
include_once("/etc/roundcube/debian-db-roundcube.php");

// The IMAP host chosen to perform the log-in.
// Leave blank to show a textbox at login, give a list of hosts
// to display a pulldown menu or set one host as string.
// To use SSL/TLS connection, enter hostname with prefix ssl:// or tls://
// Supported replacement variables:
// %n - hostname ($_SERVER['SERVER_NAME'])
// %t - hostname without the first part
// %d - domain (http hostname $_SERVER['HTTP_HOST'] without the first part)
// %s - domain name after the '@' from e-mail address provided at login screen
// For example %n = mail.domain.tld, %t = domain.tld
$config['default_host'] = array("mail.cybershit.de");

// SMTP server host (for sending mails).
// Enter hostname with prefix tls:// to use STARTTLS, or use
// prefix ssl:// to use the deprecated SSL over SMTP (aka SMTPS)
// Supported replacement variables:
// %h - user's IMAP hostname
// %n - hostname ($_SERVER['SERVER_NAME'])
// %t - hostname without the first part
// %d - domain (http hostname $_SERVER['HTTP_HOST'] without the first part)
// %z - IMAP domain (IMAP hostname without the first part)
// For example %n = mail.domain.tld, %t = domain.tld
$config['smtp_server'] = 'cybershit.de';

// SMTP port (default is 25; use 587 for STARTTLS or 465 for the
// deprecated SSL over SMTP (aka SMTPS))
$config['smtp_port'] = 25;

// SMTP username (if required) if you use %u as the username Roundcube
// will use the current username for login
$config['smtp_user'] = '';

// SMTP password (if required) if you use %p as the password Roundcube
// will use the current user's password for login
$config['smtp_pass'] = '%p';

// provide an URL where a user can get support for this Roundcube installation
// PLEASE DO NOT LINK TO THE ROUNDCUBE.NET WEBSITE HERE!
$config['support_url'] = '';

// Name your service. This is displayed on the login screen and in the window title
$config['product_name'] = 'CYBERSHIIIIT Mail Service';

// this key is used to encrypt the users imap password which is stored
// in the session record (and the client cookie if remember password is enabled).
// please provide a string of exactly 24 chars.
// YOUR KEY MUST BE DIFFERENT THAN THE SAMPLE VALUE FOR SECURITY REASONS
$config['des_key'] = '[removed for security]';

// List of active plugins (in plugins/ directory)
// Debian: install roundcube-plugins first to have any
$config['plugins'] = array(
);

// skin name: folder from skins/
$config['skin'] = 'larry';

// Disable spellchecking
// Debian: spellshecking needs additional packages to be installed, or calling external APIs
//         see defaults.inc.php for additional informations
$config['enable_spellcheck'] = false;

$config['smtp_auth_type'] = 'LOGIN';

Установка и использование Roundcube на CentOS

Обновлено Обновлено: 18.05.2023
Опубликовано Опубликовано: 05.07.2019

Тематические термины: Roundcube, NGINX, CentOS, PHP, PHP-FPM, MariaDB.

Разберем ситуацию, когда необходимо «с нуля» установить Roundcube на выделенный сервер. Сначала мы настроим его на работу с одним удаленным почтовым сервером, затем — несколькими. В данной инструкции будет применяться операционная система Linux CentOS и веб-сервер NGINX + php-fpm.

Конфигурируем веб-сервер
    NGINX
    PHP + PHP-FPM
    NGINX и PHP-FPM
Установка MariaDB
Развертывание Roundcube
Подключение по SSL и TLS
Аутентификация на MTA
Добавление почтового сервера
Смена логотипа и названия
Установка плагина для добавления писем в СПАМ
Ограничение на размер вложения
Смена пароля пользователя из веб-интерфейса
Настройки, которые могут показаться полезными
Устранение возможных ошибок

Настройка веб-сервера

Roundcube является веб-приложением и для работы требует веб-сервер. В данной инструкции мы будем использовать связку NGINX + PHP + PHP-FPM.

Установка и запуск nginx

Установку выполняем следующими командами.

yum install epel-release

yum install nginx

После установки разрешаем автозапуск nginx и стартуем его:

systemctl enable nginx

systemctl start nginx

Открываем веб-браузер на любом компьютере локальной сети и заходим по адресу http://<IP-адрес сервера> — мы должны увидеть приветствие NGINX:

Приветствие NGINX

Установка PHP и PHP-FPM

Roundcube работает как приложение php, поэтому необходимо установить его интерпретатор. Также нам нужен PHP-FPM, так как NGINX не занимается обработкой скриптов php.

Выполняем установку компонентов:

yum install php php-fpm

… после запускаем PHP-FPM:

systemctl enable php-fpm

systemctl start php-fpm

Настройка NGINX + PHP-FPM

Открываем конфигурационный файл PHP-FPM:

vi /etc/php-fpm.d/www.conf

Задаем настройку для параметра listen:

listen = /var/run/php-fpm/php-fpm.sock

Перезапускаем php-fpm:

systemctl restart php-fpm

Теперь открываем конфиг nginx:

vi /etc/nginx/conf.d/default.conf

Внутри секции server добавим:

    location ~ .php$ {
        set $root_path /usr/share/nginx/html;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $root_path$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param DOCUMENT_ROOT $root_path;
    }

Редактируем секцию location:

    location / {
        …
        index  index.php;
    }

Перезапускаем nginx и php-fpm:

systemctl restart nginx

Создаем файл index.php в root-каталоге nginx:

vi /usr/share/nginx/html/index.php

<?php phpinfo(); ?>

Открываем браузер и переходим по адресу http://<IP-адрес сервера> — должна открыться страница с отображением параметров php:

Страница phpinfo

Сервер баз данных

Также для Roundcube нужна СУБД — мы установим MariaDB:

yum install mariadb-server

Запускаем сервис базы данных + разрешаем его автозапуск:

systemctl start mariadb

systemctl enable mariadb

Задаем пароль для суперпользователя mariadb:

mysqladmin -u root password

Устанавливаем компоненты для работы php с mysql:

yum install php-mysql php-mysqli

Перезапускаем php-fpm:

systemctl restart php-fpm

Снова открываем страницу http://<IP-адрес сервера> — должен появится раздел mysql:

Поддержка mysql в phpinfo

Устанавливаем и настраиваем Roundcube Webmail

Открываем страницу загрузки Roundcube. Копируем ссылку на LTS-версию продукта (стабильную):

Копируем ссылку на LTS-версию roundcube

Используем ссылку, чтобы загрузить архив программы:

wget https://github.com/roundcube/roundcubemail/releases/download/1.1.12/roundcubemail-1.1.12-complete.tar.gz

* на момент написания инструкции LTS версия была 1.1.12.

Создаем каталог для размещения файлов Roundcube:

mkdir /usr/share/nginx/html/webmail

И распаковываем архив в созданную папку:

tar -C /usr/share/nginx/html/webmail -xvf roundcubemail-*.tar.gz —strip-components 1

Копируем шаблон конфигурационного файла и создаем рабочий конфиг:

cp /usr/share/nginx/html/webmail/config/config.inc.php.sample /usr/share/nginx/html/webmail/config/config.inc.php

Открываем его на редактирование:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Редактируем строку для подключения к СУБД: 

$config[‘db_dsnw’] = ‘mysql://roundcube:roundcube123@localhost/roundcubemail’;

* где roundcube:roundcube123 — логин и пароль для доступа к базе данных; localhost — сервер базы данных; roundcubemail — имя базы данных.

Создаем следующие строки:

$config[‘enable_installer’] = true;

$config[‘drafts_mbox’] = ‘Drafts’;
$config[‘junk_mbox’] = ‘Junk’;
$config[‘sent_mbox’] = ‘Sent’;
$config[‘trash_mbox’] = ‘Trash’;
$config[‘create_default_folders’] = true;

* первая строка разрешает установку портала. Остальные — указывают на необходимость создания папок по умолчанию, если их нет. Без данной настройки, если не создавались папки другим клиентом, веб-клиент может выдавать ошибки при перемещении писем, например, при их удалении.

Задаем владельца apache на папку портала:

chown -R apache:apache /usr/share/nginx/html/webmail

* несмотря на то, что наш сервер обрабатываем скрипты с помощью php-fpm, работает последний по умолчанию от apache.

Создаем в MariaDB базу и пользователя для roundcubemail:

mysql -uroot -p

… система запросит пароль — вводим тот, что задавали при установке MariaDB. 

> CREATE DATABASE roundcubemail DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

> GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost IDENTIFIED BY ’roundcube123′;

> quit

* данными командами мы создаем базу данных roundcubemail и пользователя roundcube с паролем roundcube123. Обратите внимание, что если в вашем случае будут использоваться другие пользователь, пароль и база данных, то следует внести соответствующие изменения в настройку самого roundcube, которую мы выполняли ранее.

Загружаем в созданную базу данные:

mysql -uroot -p roundcubemail < /usr/share/nginx/html/webmail/SQL/mysql.initial.sql

… снова запрос пароля — вводим пароль от суперпользователя MariaDB.

Устанавливаем компоненты, необходимые для работы Roundcube:

yum install php-pear php-mcrypt php-intl php-ldap php-pear-Net-SMTP php-pear-Net-IDNA2 php-pear-Mail-Mime

Настроим php:

vi /etc/php.ini

date.timezone = «Europe/Moscow»

* в данном примере мы задаем московское время.

Перезагружаем php-fpm:

systemctl restart php-fpm

Открываем браузер и переходим по адресу http://<IP-адрес сервера>/webmail/installer/.

В самом низу нажимаем по кнопке Next. Если кнопка будет неактивна, проверяем, что нет ошибок (NOT OK):

Веб-установка roundcube - проверка настроек

На следующей странице мы создаем конфигурационный файл. 

а) вводим данные для подключения к СУБД:

Веб-установка roundcube - данные для подключения к MySQL

б) настраиваем подключение к удаленному почтовому серверу:

Веб-установка roundcube - данные для подключения к IMAP

* в данном примере мы указываем сервер 192.168.0.15 с доступом по IMAP.

в) для отправки сообщений нужно использовать следующий удаленный сервер:

Веб-установка roundcube - данные для подключения к SMTP

* также указан почтовый сервер 192.168.0.15.

г) после окончания правки конфигурации, кликаем по CREATE CONFIG:

Веб-установка roundcube - create config

Конфигурационный файл создан — нажимаем CONTINUE, чтобы продолжить установку:

Веб-установка roundcube - переходим к шагу 3

Проверяем, что все пункты находятся в состоянии OK. Установка выполнена.

Открываем конфигурационный файл roundcube:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Запрещаем установку портала:

$config[‘enable_installer’] = false;

После удаляем папку с установочными скриптами:

rm -R /usr/share/nginx/html/webmail/installer

И заходим в браузере по адресу http://<IP-адрес сервера>/webmail/. — должна открыться страница аутентификации пользователя. Пока не вводим никаких данных.

SSL и TLS

Если почтовый сервер поддерживает/требует SSL или TLS соединения, то открываем конфигурационный файл roundcube:

vi /usr/share/nginx/html/webmail/config/config.inc.php

… и редактируем:


$config[‘default_host’] = ‘tls://192.168.0.15’;

$config[‘smtp_server’] = ‘ssl://192.168.0.16’;

* в данном примере мы указали, что подключение к серверу по IMAP выполняется с использованием TLS, а по SMTP — по SSL.

Открываем браузер и переходим по адресу http://<IP-адрес сервера>/webmail/. — входим в систему под пользователем и паролем одной из почтовых учетных записей. Вход должен выполнить успешно и мы должны увидеть письма, находящиеся в почтовом ящике.

Настройка аутентификации на сервере исходящей почты

Для возможности отправлять письма, многие почтовые MTA требуют авторизации пользователя. Как правило, используются логин и пароль такие же, как на подключение к почтовому ящику.

И так, Roundcube должен отправлять данные для smtp-аутентификации. Открываем конфигурационный файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Добавим такие строки:

$config[‘smtp_user’] = ‘%u’;
$config[‘smtp_pass’] = ‘%p’;

* мы указали использовать данные, под которыми зашел текущий пользователь, для авторизации на SMTP .

Переходим к нашей странице http://<IP-адрес сервера>/webmail/. — пробуем отправить письмо. Должно все получиться.

Добавление почтового сервера

Добавим еще один сервер почты в Roundcube. Открываем конфигурационный файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Находим нашу настройку:

$config[‘default_host’] = ‘tls://192.168.0.15’;

… и меняем ее на:

$config[‘default_host’] = array(‘tls://192.168.0.15’, ‘tls://192.168.0.16’);

* мы изменили тип записи, указав, что это массив (array) и через запятую перечислили два сервера — 192.168.0.15 и 192.168.0.16.

Переходим на страницу авторизации Roundcube http://<IP-адрес сервера>/webmail/. — мы должны увидеть выпадающий список наших серверов:

Выбор сервера в выпадающем списке

Несколько доменов без выпадающего списка

Как правило, пользователям неудобно выбирать нужный сервер. Это может их сбить с толку.

Чтобы Roundcube автоматически выбирал почтовый сервер, внесем изменения в наш конфигурационный файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php


$config[‘default_host’] = ‘tls://imap.%s’;

$config[‘smtp_server’] = ‘tls://smtp.%s’

* мы опять вернули старый формат для нашей записи default_host и преобразовали адрес с помощью переменной %s — она позволяет подставлять в имя сервера вторую часть (после @) вводимого email адреса. Например, если мы авторизуемся под пользователем master@dmosk.ru, то Roundcube станет подключаться к серверу imap.dmosk.ru.

Чтобы данная настройка корректно работала, необходимо, чтобы сервер мог разрешать имена серверов для подключения в IP-адреса. Для этого все хосты imap и smtp для обслуживаемых почтовых доменов должны быть в DNS-сервере, к которому обращается сервер Roundcube. Или нужные записи можно прописать в файле /etc/hosts.

Брендирование (свой логотип и название)

Roundcube можно настроить для отображения вашего логотипа и названия. Для этого открываем конфигурационный файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Добавляем строки (или редактируем):

$config[‘skin_logo’] = ‘images/logo.png’;
$config[‘product_name’] = ‘Dmosk Roundcube Webmail’;

skin_logo указывает путь относительно каталога roundcube (но если указать первым символом /, то путь будет относительно каталога с темой — это может быть полезным, если для каждой темы должен быть свой логотип); product_name — задает название в нижней части формы авторизации.

Создаем каталог для хранения изображений:

mkdir /usr/share/nginx/html/webmail/images

… и копируем туда наш логотип logo.png. Для копирования файла на сервер Linux можно воспользоваться программой WinSCP.

Открываем веб-интерфейс и проверяем, что логотип и название поменялись.

Кнопка добавления письма в СПАМ

По умолчанию, в roundcube нет возможности быстро отметить письмо как нежелательное. Для этого нужно установить плагин. Рассмотрим установку дополнения Roundcube-Plugin-Mark-as-Junk-2.

Для этого переходим на страницу проекта в GitHub и копируем ссылку на последнюю версию архива:

Ссылка на загрузку плагина Roundcube-Plugin-Mark-as-Junk-2

Используем скопированную ссылку, чтобы загрузить плагин на сервер:

wget https://github.com/johndoh/roundcube-markasjunk2/archive/master.zip

Распаковываем скачанный архив:

unzip master.zip

Переносим распакованный каталог в папку с плагинами roundcube:

mv roundcube-markasjunk2-master /usr/share/nginx/html/webmail/plugins/markasjunk2

* обратите внимание, что мы переименовываем roundcube-markasjunk2-master в markasjunk2.

Открываем конфигурационный файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php

Находим строку с плагинами:

$config[‘plugins’] 

… и дописываем в нее наш плагин:

… array(
    …
    ‘markasjunk2’,
);

Готово. Переходим в roundcube и обновляем страницу. Мы должны увидеть кнопку СПАМ в панели действий:

Кнопка СПАМ в Roundcube

Изменение размера вложения

По умолчанию, приложение может разрешать небольшой размер вложения. Предположим, нам нужно отправлять файлы объемом 30 Мб. Чтобы это сделать, выполняем следующие действия.

1. Настройка лимитов при отправке файлов в PHP.

Roundcube написан на PHP и нам необходимо убедиться, что интерпретатор не ограничивает нас в объеме загружаемых файлов. Для этого открываем файл:

vi /etc/php.ini

* в разных системах это могут быть разные пути, но мы рассматриваем установку под CentOS.

Редактируем следующие директивы:

post_max_size = 30M

upload_max_filesize = 30M

Перезапускаем интерпретатор PHP (в нашем случае это php-fpm):

systemctl restart php-fpm

2. Настраиваем Roundcube.

Открываем конфигурацию:

vi /usr/share/nginx/html/webmail/config/config.inc.php

* данный путь может отличаться для вашей системы.

Редактируем или добавляем опцию:

$config[‘max_message_size’] = ’40M’;

* обратите внимание, что необходимо установить значение max_message_size на 30-40% больше, чем желаемый максимальный размер сообщения. Это связано с тем, что в процессе отправки сообщения могут добавляться дополнительные данные (например, кодирование в base64), которые увеличивают размер сообщения.

3. Ограничения в nginx.

Если в качестве веб-сервера у нас используется nginx, то также нужно убедиться, что задана опция client_max_body_size со значением 30M или более в разделе http.

vi /etc/nginx/nginx.conf

http {
    …
    client_max_body_size 30m;
    …
}

После внесения изменений, перезагружаем веб-сервер:

nginx -t && nginx -s reload

4. Увеличение лимита отправки для MTA.

Стоит не забывать, что сам почтовый сервер также устанавливаем ограничения на размер отправляемого сообщения. В зависимости от того, какой MTA мы используем, будут различные варианты настройки.

Например, для Postfix задать лимит можно изменив значение для директивы message_size_limit. Подробнее в инструкции Лимиты в Postfix.

Веб интерфейс roundcube позволяет пользователям менять свои пароли с помощью плагина password. Данный плагин идет в стандартной поставке, но может быть не включен в конфигурации. Проверим это — открываем файл:

vi /usr/share/nginx/html/webmail/config/config.inc.php

* в вашем случае путь до конфигурационнога файла может быть другим.

Проверяем, что в перечне плагинов есть password. В противном случае, добавляем:

$config[‘plugins’] = [
    …
    ‘password’,
];

Переходим в каталог с плагином. Он находится в папке roundcube + plugins/password. В моем случае это:

cd /usr/share/nginx/html/webmail/plugins/password

Используем шаблон конфигурационного файла:

mv config.inc.php.dist config.inc.php

Открываем его и вносим правки:

vi config.inc.php

Значения для опций очень сильно зависят от вашей почтовой инфраструктуры. Я лишь, приведу пример моей конфигурации, но вам придется изучить вопрос, чтобы правильно настроить плагин.

$config[‘password_driver’] = ‘sql’;

$config[‘password_dovecotpw’] = ‘/usr/local/sbin/doveadm pw’; // for dovecot-2.x
//$config[‘password_dovecotpw’] = ‘/usr/local/sbin/dovecotpw’; // for dovecot-1.x

$config[‘password_db_dsn’] = ‘mysql://postfix:postfix123@localhost/postfix’;

$config[‘password_query’] = ‘UPDATE mailbox SET password=%c WHERE username=%u’;

* где:

  • password_driver — указываем, где хранится база с пользователями. В моем примере, SQL.
  • password_dovecotpw — нам нужно раскомментировать один из вариантов. Сейчас чаще используется dovecot версии 2, поэтому в моем примере снят комментарий с него.
  • password_db_dsn — строка подключения к базе, где находятся пользователи.
  • password_query — запрос, с помощью которого можно сменить пароль.

* в моем примере настройка выполнена для конфигурации Dovecot + MySQL.

Заходим в Roundcube. Переходим в раздел НастройкиПароль. Пробуем его сменить.

Полезные настройки

В данном разделе рассмотрим настройки, которые могут пригодиться в ходе эксплуатации roundcube. Изменения вводим в конфигурационном файле:

vi /usr/share/nginx/html/webmail/config/config.inc.php

1. Создание писем в формате HTML

По умолчанию, все письма создаются в текстовом формате. Данное поведение можно изменить в настройках пользователя. Однако, если мы хотим, чтобы у всех пользователей по умолчанию письма создавались в HTML, добавляем строку:

$config[‘htmleditor’] = 1;

* возможны варианты:

  • 0 — никогда.
  • 1 — всегда.
  • 2 — при ответе на HTML-сообщение.
  • 3 — при пересылке или ответе на HTML-сообщение.
  • 4 — всегда, кроме ответа на текстовое сообщение.

2. Время сессии

По умолчанию, время работы веб-интерфейса без необходимости вводить логин и пароль может оказаться недостаточным. Для изменения параметра редактируем директиву:

$config[‘session_lifetime’] = 1440;

* время указывается в минутах. В данном примере, 24 часа.

3. Отображение писем

Можно указать, чтобы письма по умолчанию отображались общим списком в порядке поступления или в режиме чата. За это отвечает опция:

$config[‘default_list_mode’] = ‘list’;

* возможные варианты:

  • list — список писем.
  • threads — режим чата.

Возможные ошибки

1. Неудачное соединение с IMAP сервером.

Появляется при попытке авторизоваться в Roundcube.

Причина: как правило, недоступен IMAP-сервер или Roundcube неправильно настроен на подключение к серверу.

Решение: проверяем, что сервер доступен по сети. Проверяем настройки SSL и TLS по методу, описанному выше.

2. SMTP ошибка (554): Невозможно добавить получателя XXX (5.7.1 <XXX>: Relay access denied)

Ошибка появляется при попытке отправить письмо.

Причина: SMTP-сервер не разрешает удаленному хосту отправку сообщений. Для этого требуется пройти аутентификацию.

Решение: есть два способа устранить ошибку:

1. Настроить аутентификацю в Roundcube по методу, описанному выше.

2. Также можно решить проблему, добавив наш хост Roundcube в качестве relay на почтовом сервере. Данный способ не является правильным с точки зрения безопасности и его рекомендуется применить для временного использования.

В качестве SMTP-сервера могут использоваться разные MTA. Приведем пример для разрешения отправки писем в Postfix. Открываем его конфигурационный файл:

vi /etc/postfix/main.cf

Редактируем строку mynetworks:

mynetworks = … 192.168.0.14

* где mynetworks — список доверенных узлов, которым можно будет отправлять сообщения без дополнительных проверок. В данном примере мы добавили хост 192.168.0.14.

Перечитываем конфигурацию postfix:

systemctl reload postfix

Skip to forum content

iRedMail

Works on CentOS, Rocky, Debian, Ubuntu, FreeBSD, OpenBSD

You are not logged in. Please login or register.

May 23, 2023: iRedMail-1.6.3 has been released.



  • Spider Email Archiver: Lightweight on-premises email archiving software, developed by iRedMail team.
  • Join our Telegram group (@iredmail_chat) to get help from other iRedMail users.

Pages 1

You must login or register to post a reply

1 2015-04-15 05:07:39 (edited by landroid 2015-04-15 05:09:48)

  • landroid
  • Member
  • Offline
  • Registered: 2015-04-15
  • Posts: 2

Topic: Return receipt in roundcube SMTP Error (554)

======== Required information ====
— iRedMail version:0.9.0
— Store mail accounts in which backend (LDAP):
— Web server (Apache):
— Linux/BSD distribution name and version: CentOS 7.0
— Related log if you’re reporting an issue:
====
When using roundcube
—————————-
The sender of this message has asked to be notified when you read this message. Do you wish to notify the sender?
SMTP Error (554): Failed to add recipient «my mail address» (5.7.1 <my mail address>: Recipient address rejected: Access denied).

help solve the problem

—-

Spider Email Archiver: On-Premises, lightweight email archiving software developed by iRedMail team. Stable release is out.

2 Reply by ZhangHuangbin 2015-04-15 21:17:22

  • ZhangHuangbin
  • ZhangHuangbin
  • iRedMail Developers
  • Offline
  • Registered: 2009-05-06
  • Posts: 30,314

Re: Return receipt in roundcube SMTP Error (554)

Add below setting in /var/www/roundcubemail/config/config.inc.php should fix this issue:

$config['mdn_use_from'] = true;

3 Reply by landroid 2015-04-15 22:12:57

  • landroid
  • Member
  • Offline
  • Registered: 2015-04-15
  • Posts: 2

Re: Return receipt in roundcube SMTP Error (554)

Thank you very much!

Posts: 3

Pages 1

You must login or register to post a reply

Generated in 0.010 seconds (43% PHP — 57% DB) with 8 queries

Понравилась статья? Поделить с друзьями:
  • Roundcube smtp ошибка 250 ошибка авторизации
  • Rotoplat 507 ошибки
  • Rotoplat 407 ошибки
  • Ross tech расшифровка ошибок
  • Ross tech wiki ошибки