Migrar una lista de correo a Discourse (mbox, Listserv, Google Groups, etc)

This guide is for you if you want to migrate a mailing list to Discourse.
It also contains instructions for importing messages from image Google Groups.

1. Importing using Docker container

This is the recommended way for importing content from your mailing lists into Discourse.

1.1. Installing Discourse

:bulb: The import script most likely won’t work on systems with less than 4GB of RAM. Recommended are 8GB of RAM or more. You can scale back the RAM usage after the import if you like.

Install Discourse by following the official installation guide. Afterwards it’s a good idea to go to the Admin section and configure a few settings:

  • Enable login_required if imported topics shouldn’t be visible to the public

  • Enable hide_user_profiles_from_public if user profiles shouldn’t be visible to the public.

  • Disable download_remote_images_to_local if you don’t want Discourse to download images embedded in posts.

  • Enable disable_edit_notifications if you enabled download_remote_images_to_local and don’t want your users to get lots of notifications about posts edited by the system user.

  • Change the value of slug_generation_method if most of the topic titles use characters which shouldn’t be mapped to ASCII (e.g. Arabic). See this post for more information.

:bangbang: The following steps assume that you installed Discourse on Ubuntu and that you are connected to the machine via SSH or have direct access to the machine’s terminal.

1.2. Preparing the Docker container

Copy the container configuration file app.yml to import.yml and edit it with your favorite editor.

cd /var/discourse
cp containers/app.yml containers/import.yml
nano containers/import.yml
Regular import

Add - "templates/import/mbox.template.yml" to the list of templates. Afterwards it should look something like this:

templates:
  - "templates/postgres.template.yml"
  - "templates/redis.template.yml"
  - "templates/web.template.yml"
  - "templates/web.ratelimited.template.yml"
## Uncomment these two lines if you wish to add Lets Encrypt (https)
  #- "templates/web.ssl.template.yml"
  #- "templates/web.letsencrypt.ssl.template.yml"
  - "templates/import/mbox.template.yml"

That’s it. You can save the file, close the editor and build the container.

Google Groups import

You need to add two entries to the list of templates:

  - "templates/import/chrome-dep.template.yml"
  - "templates/import/mbox.template.yml"

Afterwards it should look something like this:

templates:
  - "templates/postgres.template.yml"
  - "templates/redis.template.yml"
  - "templates/web.template.yml"
  - "templates/web.ratelimited.template.yml"
## Uncomment these two lines if you wish to add Lets Encrypt (https)
  #- "templates/web.ssl.template.yml"
  #- "templates/web.letsencrypt.ssl.template.yml"
  - "templates/import/chrome-dep.template.yml"
  - "templates/import/mbox.template.yml"

That’s it. You can save the file, close the editor and build the container.

/var/discourse/launcher stop app
/var/discourse/launcher rebuild import

Building the container creates an import directory within the container’s shared directory. It looks like this:

/var/discourse/shared/standalone/import
├── data
└── settings.yml

1.3. Downloading messages from Google Groups (optional)

You can skip this step unless you want to migrate from image Google Groups.

Instructions for Google Groups

1.3.1. Preparation

:warning: Make sure you don’t have any pinned posts in your group, otherwise the crawler might fail to download some or all messages.

:warning: Make sure the group settings allow posting, otherwise you might see “Failed to scrape message” error messages. It might take a couple of minutes before the scraping works when you changed those settings recently.

Google account: You need a Google account that has the Manager or Owner role for your Google Group, otherwise the downloaded messages will contain censored email addresses.

Group name: You can find the group name by visiting your Google Group and looking at the browser’s address bar. image

Domain name: The URL might look a little bit differently if you are a G Suite customer. You need to know the domain name if the URL contains something like example.com. image

1.3.2 Cookies :cookie:

In order to download messages, the crawler needs to have access to a Google account that has the owner role for your group. Please visit https://myaccount.google.com/ in your browser and sign in if you aren’t already logged in. Then use a browser extension of your choice to export your cookies for google.com in a file named cookies.txt.

The recommended browser extensions is Export Cookies for Mozilla Firefox.

Upload the cookies.txt file to your server and save it within the /var/discourse/shared/standalone/import directory.

1.3.3. Download messages

:bulb: Tip: It’s a good idea to download messages inside a tmux or screen session, so that you can reconnect to the session in case of SSH connection loss.

Let’s start by entering the Docker container.

/var/discourse/launcher enter import

Replace the <group_name> (and if applicable, the <domain_name>) placeholders within the following command with the group name and domain name from step 1.3.1 and execute it inside the Docker container in order to start the download of messages.

If you didn’t find a domain name in step 1.3.1, this is the command for you:

script/import_scripts/google_groups.rb -g <group_name>

Or, if you found a domain name in step 1.3.1, use this command instead:

script/import_scripts/google_groups.rb -g <group_name> -d <domain_name>

Downloading all messages can take a long time. It mostly depends on the number of topics in your Google Group. The script will show you a message like this when it’s finished: Done (00h 26min 52sec)

:bulb: Tip: You can abort the download anytime you want by pressing Ctrl+C
When you restart the download it will continue where it left off.

1.4. Configuring the importer

You can configure the importer by editing the example settings.yml file that has been copied into the import directory.

nano /var/discourse/shared/standalone/import/settings.yml

The settings file comes with sensible defaults, but here are a few tips anyway:

  • The settings file contains multiple examples on how to split data files:

    • mbox files usually are separated by a From header. Choose a regular expression that works for your files.

    • If each of your files contains only one message, set the split_regex to an empty string. This also applies to imports from image Google Groups.

    • There’s also an example for files from the popular Listserv mailing list software.

  • prefer_html allows you to configure if the import should use the HTML part of emails when it exists. You should choose what suits you best – it heavily depends on the emails sent to your mailing list.

  • By default each user imported from the mailing list is created as staged user. You can disable that behaviour by setting staged to false.

  • If your emails do not contain a Message-ID header (like messages stored by Listserv), you should enable the group_messages_by_subject setting.

1.5. Prepare files

Each subdirectory of /var/discourse/shared/standalone/import/data gets imported as its own category and each directory should contain the data files you want to import. The file names of those do not matter.

Example: The import directory should look like this if you want to import two mailing lists with multiple mbox files:

/var/discourse/shared/standalone/import
├── data
│   ├── list 1
│   │   ├── foo
│   │   ├── bar
│   ├── list 2
│   │   ├── 2017-12.mbox
│   │   ├── 2018-01.mbox
└── settings.yml

1.6. Executing the import script

:bulb: Tip: It’s a good idea to start the import inside a tmux or screen session, so that you can reconnect to the session in case of SSH connection loss.

Let’s start the import by entering the Docker container and launching the import script inside the Docker container.

/var/discourse/launcher enter import
import_mbox.sh # inside the Docker container

Depending on the size of your mailing lists it’s now time for some :coffee: or :sleeping:
The import script will show you a message like this when it’s finished: Done (00h 26min 52sec)

:bulb: Tip: You can abort the import anytime you want by pressing Ctrl+C
When you restart the import it will continue where it left off.

You can exit and stop the Docker container after the import has finished.

exit # inside the Docker container
/var/discourse/launcher stop import

1.7. Starting Discourse

Let’s start the app container and take a look at the imported data.

/var/discourse/launcher start app

Discourse will start and Sidekiq will begin post-processing all the imported posts. This can take a considerate amount of time. You can watch the progress by logging in as admin and visiting http://discourse.example.com/sidekiq

1.8. Clean up

So, you are satisfied with the result of the import and want to free some disk space? The following commands will delete the Docker container used for importing as well as all the files used during the import.

/var/discourse/launcher destroy import
rm /var/discourse/containers/import.yml
rm -R /var/discourse/shared/standalone/import

1.9. The End

Now it’s time to celebrate and enjoy your new Discourse instance! :tada:

2. FAQ

2.1. How can I remove list names (e.g. [Foo]) from topic titles during the import?

You can use an empty tag to remove one or more prefixes from topic titles. The settings file contains an example.

2.2 How can I prevent the import script from detecting messages as already being imported?

:warning: The following steps will reset your Discourse forum to the initial state! You will need to start from scratch.

The following commands will stop the container, delete everything except the mbox files and the importer configuration and restart the container.

Commands
cd /var/discourse

./launcher stop app
./launcher stop import

rm -r ./shared/standalone/!(import)
rm ./shared/standalone/import/data/index.db

./launcher rebuild import

./launcher enter import
import_mbox.sh # inside the Docker container

2.3 How can I manipulate messages before they are imported into Discourse?

Enable index_only in settings.yml and take a look at the index.db (a SQLite database) before you run the actual import.

You can use SQL to update missing values in the database if you want. That way you don’t need to reindex any messages. The script uses only data from the index.db during the import phase. Simply disable the index_only option when you are done and rerun the importer. It will skip the indexing if none of the mbox files were changed, recalculate the content of the user and email_order tables and start the actual import process.

2.4 How can I find messages which cause problems during the import?

You can split mbox files into individual files to make it easier to find offending emails.

Commands
apt install procmail;
export FILENO=0000;
formail -ds sh -c 'cat &gt; split/msg.$FILENO' < mbox;

2.5 I have already imported a group. How can I import another group?

Create a new directory in the import/data directory and restart the import script.

2.6 I don’t have access to Mailman archives in mbox format? Is there any other way to get them?

You could give this script a try.

Last edited by @JammyDodger 2024-05-27T14:56:11Z

Check documentPerform check on document:
30 Me gusta

@gerhard - I was able to migrate an mbox archive of 22,000 messages using this script on a Digital Ocean droplet with only 1GB RAM. No problems. Thank you for the write-up of instructions. Everything worked great. The only mistake I made on my first attempt was trying to name the /var/discourse/shared/standalone/import/data/X subfolder using a new category I created before running the script. That caused the import to place these messages into the Uncategorized category. On second attempt, I deleted the new category and tried again. This created the category name for me and placed the messages into the proper category automatically.

6 Me gusta

Gracias por esta guía.

Estoy intentando realizar una importación de Google Groups. Desafortunadamente, me encuentro con este error al ejecutar import_mbox.sh:

La importación de mbox está comenzando...

Rastreo (el más reciente al final):
5: desde script/import_scripts/mbox.rb:9:in `<main>'
4: desde script/import_scripts/mbox.rb:10:in `<module:ImportScripts>'
3: desde script/import_scripts/mbox.rb:13:in `<module:Mbox>'
2: desde /var/www/discourse/script/import_scripts/mbox/support/settings.rb:9:in `load'
1: desde /var/www/discourse/script/import_scripts/mbox/support/settings.rb:9:in `new'

/var/www/discourse/script/import_scripts/mbox/support/settings.rb:42:in `initialize': método `each' no definido para nil:NilClass (NoMethodError)

Sin embargo, todos los archivos en /var/discourse/shared/standalone/import/data/Foo son archivos .eml, no mbox. ¿Eso importa?

¡Gracias!

La última versión del script de importación soluciona ese problema. Como alternativa, actualiza tu archivo de configuración. Se han realizado algunos cambios recientes.

5 Me gusta

Muchas gracias. ¿Podrías darme algún consejo sobre cómo actualizar el script de importación?

¿Es suficiente con actualizar solo los scripts de importación o tengo que rehacer más pasos de la guía (¿cuáles?)? No logro encontrarlos y, por lo tanto, no sé cómo actualizarlos.

Actualicé el archivo de configuración como mencionaste que era una alternativa, pero sigo teniendo los mismos problemas.

Gracias.

Puedes ejecutar /var/discourse/launcher rebuild import para actualizar el script de importación y todo lo demás relacionado con él.

4 Me gusta

Gracias.

Al ejecutar import_mbox.sh, casi todos los mensajes se omiten con mensajes como el siguiente:

script/import_scripts/mbox.rb:12:in `<module:Mbox>'

script/import_scripts/mbox.rb:10:in `<module:ImportScripts>'

script/import_scripts/mbox.rb:9:in `<main>'

41 / 215 ( 19.1%) [59096 items/min] No se pudo mapear el post para 36a37072-e5b6-4009-878f-f0824e40eac6@googlegroups.com

undefined method `each' for nil:NilClass

/var/www/discourse/script/import_scripts/mbox/importer.rb:179:in `block in remove_tags!'

/var/www/discourse/script/import_scripts/mbox/importer.rb:176:in `loop'

/var/www/discourse/script/import_scripts/mbox/importer.rb:176:in `remove_tags!'

/var/www/discourse/script/import_scripts/mbox/importer.rb:150:in `map_first_post'

/var/www/discourse/script/import_scripts/mbox/importer.rb:104:in `block (2 levels) in import_posts'

/var/www/discourse/script/import_scripts/base.rb:503:in `block in create_posts'

/var/www/discourse/script/import_scripts/base.rb:502:in `each'

/var/www/discourse/script/import_scripts/base.rb:502:in `create_posts'

/var/www/discourse/script/import_scripts/mbox/importer.rb:98:in `block in import_posts'

/var/www/discourse/script/import_scripts/base.rb:882:in `block in batches'

/var/www/discourse/script/import_scripts/base.rb:881:in `loop'

/var/www/discourse/script/import_scripts/base.rb:881:in `batches'

/var/www/discourse/script/import_scripts/mbox/importer.rb:84:in `batches'

/var/www/discourse/script/import_scripts/mbox/importer.rb:92:in `import_posts'

/var/www/discourse/script/import_scripts/mbox/importer.rb:36:in `execute'

/var/www/discourse/script/import_scripts/base.rb:47:in `perform'

Y más adelante:

60 / 215 ( 27.9%) [58321 items/min] El mensaje padre 1b46f337-95a3-4b4a-a14a-689636941580@googlegroups.com no existe. Se omite 5634208e-e6df-4bd8-b361-0735f73fe554@googlegroups.com:

¿Cuál podría ser la razón de esto? Gracias.

El problema debería estar solucionado. Por favor, reconstruye tu contenedor de importación una vez más.

6 Me gusta

¡Genial, funcionó a la perfección! :pray: Muchas gracias por tu apoyo.

5 Me gusta

Estoy intentando descargar Google Groups y me aparece el siguiente mensaje:

Error al iniciar sesión. Por favor, verifica el contenido de tu archivo cookies.txt

He utilizado la extensión recomendada de Firefox para descargar las cookies. Lo hice ayer y hoy de nuevo. He confirmado que el archivo se está leyendo correctamente al renombrarlo con un nombre incorrecto y obtener un error de “archivo no encontrado”. He descargado todas las cookies, no solo las de Google. Me he cerrado sesión y he vuelto a iniciarla, y he vuelto a descargar las cookies.

Puedo ver que soy administrador porque tengo las opciones de “gestionar grupo”.

He verificado tres veces que estoy usando el nombre correcto del grupo, copiándolo y pegándolo, y comprobando que tiene el formato de nombre de grupo y no el de nombre de dominio.

¿Algo está roto o el problema es solo mío?

@gerhard, perdona por mencionarte, pero ¿tienes alguna sugerencia rápida sobre cómo depurar esto? ¿Quizás haya cambiado algún endpoint de inicio de sesión?

EDITADO: Lo encontré. Presentaré una PR en breve. El endpoint de inicio de sesión ha cambiado y logré adivinar el nuevo. :slight_smile:

1 me gusta

Novato intentando importar archivos mbox de Yahoo Groups. He seguido estas instrucciones varias veces, pero siempre con el mismo mensaje de error. He visto que otros han tenido éxito, así que probablemente sea un error de principiante. El error parece indicar que split_regex: "^From .+@.+" no está encontrando la clave de correo electrónico para dividir el archivo, pero probé la expresión regular en un editor de texto y funciona como se esperaba. La línea 2 del archivo de importación es similar a Message-ID: <35690.0.1.959300741@eGroups.com>.

¿Alguna idea? Gracias de antemano…

La importación de mbox está comenzando...

Traceback (última llamada más reciente):
	12: desde script/import_scripts/mbox.rb:9:in `<main>'
	11: desde script/import_scripts/mbox.rb:10:in `<module:ImportScripts>'
	10: desde script/import_scripts/mbox.rb:12:in `<module:Mbox>'
	 9: desde script/import_scripts/mbox.rb:12:in `new'
	 8: desde /var/www/discourse/script/import_scripts/mbox/importer.rb:11:in `initialize'
	 7: desde /var/www/discourse/script/import_scripts/mbox/support/settings.rb:8:in `load'
	 6: desde /usr/local/lib/ruby/2.6.0/psych.rb:577:in `load_file'
	 5: desde /usr/local/lib/ruby/2.6.0/psych.rb:577:in `open'
	 4: desde /usr/local/lib/ruby/2.6.0/psych.rb:578:in `block in load_file'
	 3: desde /usr/local/lib/ruby/2.6.0/psych.rb:277:in `load'
	 2: desde /usr/local/lib/ruby/2.6.0/psych.rb:390:in `parse'
	 1: desde /usr/local/lib/ruby/2.6.0/psych.rb:456:in `parse_stream'
/usr/local/lib/ruby/2.6.0/psych.rb:456:in `parse': (/shared/import/settings.yml): no se encontró la clave esperada al analizar un mapeo de bloque en la línea 2 columna 1 (Psych::SyntaxError)

Parece que has cometido un error en el archivo settings.yml. Te sugiero validar la configuración en http://www.yamllint.com/

3 Me gusta

Gracias @gerhard. Suspiro… Debería haber visto ese problema, es mi primer encuentro con Ruby. Ahora, creo que estoy un poco más cerca, pero hay un error diferente (ver abajo). Dado que el script de importación ahora está cargando Grupos, etc., asumo que el nuevo error ocurre después del problema inicial. También asumo que el archivo de base de datos al que se hace referencia es import/index.db, creado por el script de importación (pero no se ha creado).

La importación de mbox está comenzando...

Cargando grupos existentes...
Cargando usuarios existentes...
Cargando categorías existentes...
Cargando publicaciones existentes...
Cargando temas existentes...
Traceback (última llamada desde):
	9: desde script/import_scripts/mbox.rb:9:in `<main>'
	8: desde script/import_scripts/mbox.rb:10:in `<module:ImportScripts>'
	7: desde script/import_scripts/mbox.rb:12:in `<module:Mbox>'
	6: desde script/import_scripts/mbox.rb:12:in `new'
	5: desde /var/www/discourse/script/import_scripts/mbox/importer.rb:14:in `initialize'
	4: desde /var/www/discourse/script/import_scripts/mbox/importer.rb:14:in `new'
	3: desde /var/www/discourse/script/import_scripts/mbox/support/database.rb:10:in `initialize'
	2: desde /var/www/discourse/script/import_scripts/mbox/support/database.rb:10:in `new'
	1: desde /var/www/discourse/vendor/bundle/ruby/2.6.0/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:89:in `initialize'
/var/www/discourse/vendor/bundle/ruby/2.6.0/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:89:in `open_v2': no se pudo abrir el archivo de la base de datos (SQLite3::CantOpenException)
1 me gusta

El SISTEMA no me permite editar mi comentario, así que estoy enviando esta respuesta en su lugar.

EDITO: Para cerrar el ciclo… Mi importación del grupo de Yahoo ahora funciona, al menos hasta el punto de indexar 9951 correos electrónicos. Aún no he finalizado la importación completa, así que habrá más novedades. He editado settings.yml muchas veces y ahora he vuelto a la configuración original, que de repente parece funcionar ¡sin el error de sintaxis! No entiendo por qué he recibido numerosos mensajes de error que me parecen inconsistentes. El error de sintaxis original en settings.yml sigue siendo un misterio. El mensaje de error anterior no tiene sentido para mí… suspiro.

1 me gusta

@gerhard. Creo que he encontrado una forma mucho más sencilla de hacer exactamente lo mismo que tu guía, pero sin necesidad de conocimientos técnicos ni de acceso de administrador a ningún servidor. Dime qué te parece.

Resumen

Básicamente configuraremos una lista de correo y luego usaremos un archivo de correo electrónico para enviar conversaciones pasadas en orden. Esos correos se reenviarán, pero no como lo hace el botón “Reenviar” de los clientes de correo (que sobrescribiría las cabeceras y arruinaría la sangría). Lo que queremos hacer es volver a enviarlos (enviarlos como si hubieran sido enviados a Discourse desde el principio).

Requisitos y suposiciones

  • Acceso a los intercambios de correo anteriores: alguien que los tenga almacenados en su cliente de correo y pueda ofrecerse a reenviarlos — llamémosle Juan Pérez.

  • Tiempo: el reenvío de correos será muy lento para que Discourse pueda manejarlo (quizás unos días con una computadora ejecutando la carga de los correos, dependiendo del tamaño del archivo).

  • Cliente Thunderbird: También asumimos aquí que Juan Pérez utiliza el cliente de correo “Thunderbird”. Puede que sea posible hacerlo con otros clientes, pero no lo he investigado.

La siguiente guía utiliza dos direcciones de correo como marcadores de posición. Debes reemplazarlas con tus direcciones reales.

:incoming_envelope: johndoe@example.com Correo de Juan Pérez (la persona que reenviará todo el archivo de la lista de correo)

:postbox: discourse+mailinglist-3@discoursemail.com Correo de Discourse para reenviar correos a la categoría de la lista de correo (consulta la configuración 1 para saber cómo obtenerlo)

Instrucciones

Aquí tienes un resumen básico de las instrucciones:

  1. Sigue la guía en Mirroring a read-only mailing list in Discourse para crear un espejo de tu lista de correo.

    Nota: esto solo espejará tu lista de correo hacia adelante. Todavía te perderás las conversaciones pasadas. Para eso sirve el resto de esta guía.

  2. Cambia la forma en que Discourse reenvía los correos a (no estoy realmente seguro de que esto sea necesario).
    forwarded_behavior

  3. Edita la configuración de la categoría y, bajo la opción Dirección de correo entrante personalizada:, agrega al final de lo que haya |johndoe@example.com.

    El pipe aquí funciona como un ,, es decir, que también quieres que johndoe@example.com pueda enviar a esa categoría.

  4. Juan Pérez instala en Thunderbird la extensión Mail Redirect.

    Esto es porque no es un reenvío de correo regular. Lo que hará es enviar el correo como si hubiera ido a la dirección de correo de Discourse desde el principio, en lugar de a la de Juan Pérez.

  5. Juan Pérez va a la configuración de la extensión y establece lo siguiente en 1 (el valor predeterminado es 5).
    mail_redirect

    Esto asegurará que las respuestas lleguen en orden: de lo contrario, Discourse no es lo suficientemente rápido para darse cuenta de que las respuestas están encadenadas y simplemente crea un nuevo tema para cada respuesta, pero hará que el proceso de reenvío sea muy lento.

  6. Juan Pérez selecciona todos los correos pasados de la lista de correo, hace clic derecho y selecciona Redirigir. Luego se abrirá una nueva ventana y él agregará discourse+mailinglist-3@discoursemail.com como Reenviar a.

Después de esto, el cliente de correo de Juan Pérez enviará lentamente los archivos de correo a Discourse. Solo revisa después de un tiempo para ver si la categoría de Discourse se está llenando con conversaciones antiguas y nostálgicas.

Limpieza

  • Elimina el correo de Juan Pérez de la configuración Dirección de correo entrante personalizada: de esa categoría (y no olvides eliminar el |).

  • Desinstala la extensión Mail Redirect — probablemente no la volverás a necesitar, o al menos aumenta de nuevo las conexiones SMTP a 5.

5 Me gusta

Estamos intentando migrar nuestras listas de Mailman a una instancia de Discourse que ya está en funcionamiento. Hay varias listas privadas incluidas para las cuales necesitamos configurar los permisos en la categoría correspondiente. Al crear esas categorías antes de la importación, todas las publicaciones de las listas privadas se agregan a “Sin categoría” (por lo tanto, automáticamente públicas).

Así que tenemos dos preguntas alternativas:

  • ¿Existe alguna forma de establecer permisos para las listas de correo importadas (si fueran visibles solo para administradores, ya sería suficiente para nosotros) antes de la importación?
  • ¿Existe alguna forma de agregar la lista de correo a una categoría existente (con permisos predefinidos)?
3 Me gusta

Mi Discourse es la continuación de un grupo de Yahoo, que a su vez era la continuación de un listserv de AOL. El otoño pasado, ante la gran purga de Yahoo, pude descargar un archivo .mbox del grupo de Yahoo e importar esos mensajes siguiendo estas instrucciones. Ahora he obtenido un archivo parcial del listserv de AOL y me gustaría importar esos mensajes también.

Fácil, ¿verdad? Solo hay que crear import/data/foo, colocar los mensajes allí y ejecutar el script de importación. Pero lo que me pregunto es: si más adelante logro obtener un archivo completo (o más completo), ¿puedo simplemente colocar esos archivos en import/data/foo, ejecutar nuevamente el script de importación y que agregue los nuevos mensajes a la misma categoría?

  • ¿Eliminará duplicados? ¿O veré múltiples copias de los mensajes que aparecieron en ambos archivos?
    • ¿Cambiaría la respuesta a esta pregunta si uno, el otro o ambos archivos carecieran de encabezados message-id?
  • ¿Una nueva importación en la misma categoría sobrescribiría los mensajes existentes?
  • La mayoría de mis usuarios están en modo lista de correo. Si no quiero bombardearlos con cientos (o miles) de notificaciones, sin mencionar generar una factura costosa de Mailgun, supongo que querré desactivar el correo electrónico en todo el sitio mientras se realiza la importación.
3 Me gusta

Lamentablemente, eso no es posible.

Sí, puedes engañar al script de importación para que reutilice categorías existentes.

./launcher enter app
rails c

# Usa el ID de categoría que aparece en la URL, por ejemplo
# es 56 cuando la ruta de la categoría se ve así: /c/howto/devs/56
category = Category.find(56)

# Usa el nombre del directorio donde se almacenan los archivos mbox. Por ejemplo,
# si los archivos están en import/data/foo, debes usar "foo" como nombre del directorio.
category.custom_fields["import_id"] = "nombre_del_directorio"
category.save!

Eso es inesperado. Nunca he visto que eso ocurra, pero nunca he intentado importar en categorías existentes con permisos distintos a los predeterminados.

Si no logras que funcione, te sugiero publicar un anuncio en tu foro, poner tu sitio en modo de solo lectura, crear una copia de seguridad, restaurarla en un servidor diferente, ejecutar la importación, configurar los permisos de la categoría, crear otra copia de seguridad y restaurarla en tu sitio de producción.

3 Me gusta

Sí, puedes. Es posible que quieras mantener el archivo import/data/index.db a mano, por si acaso deseas revisar los datos importados anteriormente, necesitas modificar los IDs de mensajes generados o cualquier otra cosa…

Sí, no importaría los mensajes ya importados siempre que el encabezado Message-ID permanezca igual. Si el encabezado Message-ID falta en solo uno de los archivos, tendrás mala suerte. Utilizamos el hash MD5 del mensaje si falta el encabezado. Deberás asegurarte de que ambos mensajes tengan el mismo encabezado Message-ID o generen el mismo hash MD5.

No.

Todos los correos electrónicos salientes están desactivados durante las importaciones.

3 Me gusta

Sí, puedes engañar al script de importación para que reutilice categorías existentes.

Ok, eso es básicamente lo que finalmente hicimos (usamos Category.find_by_name() en su lugar, pero supongo que eso es solo semántica). Es bueno saber que elegimos la forma “correcta” :wink: . ¡Gracias!

3 Me gusta